Kivy访问从.kv文件到.py文件的ID



。我是kivy的新手,我想做一个安卓应用程序。我几乎完成了GUI,前端部分,但我有一个很大的问题。我在网上找了很多遍,但都没有回音。我不知道如何从.kv访问id以将其用于.py函数
我在网上找到的东西都试过了,但都没用。我想从.kv文件访问id来使用它们。例如,我有一个配置文件屏幕,用户在其中写下他的名字和姓氏,在下一个页面中,我想通过使用一个函数来显示他的名字和姓。这是.kv配置文件页面:


<Profile>
FloatLayout:
canvas.before:
Color:
rgba:(1,1,1,1)

Rectangle:
source:"CreateProfileImg.png"
size: root.width, root.height
pos: self.pos 


Label:
pos_hint: {"top": 1, "left": 1}
size_hint: 1, .1
text:"Create your profile"
font_size: 65
font_name:"FreeSansBoldOblique-BYJ3.otf"
color: rgba(247,251,246,255)
id: profile_label

Label:
text: "First Name: "
font_size: 45
color: rgba(247,251,246,255)
size_hint: 0.1, 0.1
pos_hint: {"x":0.20, "top":0.8}
TextInput:
id: name
multiline: False
size_hint: 0.5, 0.1
pos_hint: {"x": 0.35, "top": 0.8}

Label:
text: "Last Name: "
font_size: 45
color: rgba(247,251,246,255)
size_hint: 0.1, 0.1
pos_hint: {"x":0.16, "top":0.7}
TextInput:
id: prenume
multiline: False
size_hint: 0.5, 0.1
pos_hint: {"x": 0.35, "top": 0.7}


Label:
text: "Currency: "
font_size: 45
color: rgba(247,251,246,255)
size_hint: 0.1, 0.1
pos_hint: {"x":0.18, "top":0.6}
Spinner:
id: moneda
text:"Select currency"
color: 0, 0, 0 ,1
background_normal:"MoneyButton.png"
size_hint: 0.5, 0.1
pos_hint:  {"x":0.35, "top":0.6}
values: ['Ron', 'Euro', 'Dolar','Lira Sterlina']
sync_height: True
#on_text: root.currency_clicked(moneda.text)

GridLayout:
rows:1
pos_hint:{"top": .2, "left": 1}
size_hint: 1, .2
ImageButton:
source:"Next_Button_On_Press.png"
on_press:
self.source = "Next_Button_On_Release.png"
app.printname()
on_release:
self.source = "Next_Button_On_Press.png"
app.change_screen("page1")

我有更多的.kv文件和很多id,但我想如果我学会了如何使用这两个,下一个会更容易。我想指定我有一个"main.kv",它包含:1。名称2.ids从我所有的.kv文件。我使用这些id在页面之间导航。

这是代码:

#:include homescreen.kv
#:include page1.kv
#:include profile.kv
GridLayout:
cols: 1
ScreenManager:
id: screen_manager
HomeScreen:
name: "home_screen"
id: home_screen
Profile:
name: "profile"
id: profile
Page1:
name: "page1"
id: page1

让我最后一次解释一下我想做什么,也许对你理解和帮助我很有用。正如你所看到的,在"个人资料"中,我有3个id。当从用户处获取TextInput时,这些id存储信息。我想在下一页中使用这些信息,在那里我想说[["你好"+ids]]

So, please help me!! Make me to understand!

几年前,当我第一次学习Kivy时,我也遇到了这个问题,但我终于找到了办法。需要一点锅炉板来保持连接。

在本例中,my_label是一个kivy id,我将它连接到一个同名的Python对象。这是通过以下行完成的:my_label:my_label

<Screen2>:
# Python: KIVY id(s)
my_label: my_label
BoxLayout:
Label:
text: "Screen2"
MDLabel:
id: my_label
text: "-"

在与该对象匹配的Python代码中,类定义l my_label:MDLabel中有一行其提供类型提示。如果您使用的是像PyCharm这样的IDE,这可以帮助您根据对象类型在代码中进行自动完成。

class Screen2(Screen):
my_label: MDLabel
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.my_label.text = "test"

并且线self.my_label.text=";测试";当然是为了展示如何使用该对象。

您还可以做更复杂的事情,例如将kv布局中的多个项目放入列表甚至字典中。kivy代码:

# a list of spinners kv_spinner_list is a ListProperty
kv_spinner_list: [kv_spinner_0, kv_spinner_1, kv_spinner_2,]

这可以是一种更有组织的方式,将多个项目引入Python代码中。

最新更新