从另一个小部件更改Kivy小部件属性
我有一个屏幕组件,上面有一个按钮(ID是:display_name),这个按钮有一个文本属性。当我按下这个按钮时,会弹出一个模态框,里面有一个文本输入框和一个按钮。我想在模态框的文本输入框里输入一些文字,然后在按下模态框的按钮时,把这些文字显示在屏幕组件的按钮上。但是我在从模态框更改屏幕按钮的文本属性时遇到了困难。我该怎么做呢?我试过下面的代码,但出现了这个错误:
AttributeError: 'kivy.properties.ObjectProperty' object has no attribute 'text'
kv代码
<ProfileScreen>:
display_name: display_name
GeneralBoxLayout:
BoxLayout:
GridLayout:
BackButton:
on_release: root.manager.current = 'home'
size_hint: (0.1,1.0)
Image:
size_hint: (0.1,1.0)
Image:
source: 'img/logo4.png'
size_hint: (0.60,1.0)
Image:
size_hint: (0.05,1.0)
MenuButton:
size_hint: (0.15,1.0)
on_release: app.build_profile_screen(); root.manager.current = 'profile'
BoxLayout:
ScrollView:
size_hint: (1,.93)
GridLayout:
BoxLayout:
Button:
id: display_name
font_size: '14sp'
text_size: (290, 40)
halign: 'left'
background_normal: 'img/white_button1.png'
background_down: 'img/white_button1.png'
border: 20,20,20,20
markup: True
on_release: app.update_display_name_popup()
<UpdateDisplayNamePopup>:
updated_display_name: updated_display_name
size_hint: .5, .3
BoxLayout:
padding: [10,10,10,10]
orientation: 'vertical'
TextInput:
id: updated_display_name
hint_text: 'Enter New Display Name'
Button:
font_size: '14sp'
text: 'Update Display Name'
background_normal: 'img/green_button5.png'
background_down: 'img/green_button5.png'
size_hint_y: None
on_release: root.update_display_name(); root.dismiss()
main.py代码
from kivy.properties import ObjectProperty
class ProfileScreen(Screen):
display_name = ObjectProperty(None)
class UpdateDisplayNamePopup(ModalView):
def update_display_name(self):
ProfileScreen.display_name.text = self.updated_display_name.text
1 个回答
2
我通过把更新显示名称的方法移到ProfileScreen类里来解决这个问题,然后从弹出窗口的按钮调用这个方法,并把更新后的显示名称文本传递给这个方法,具体做法如下:
main.py
class ProfileScreen(Screen):
def update_display_name(self, updated_display_name):
self.display_name.text = updated_display_name
kv文件
Button:
on_release: app.root.get_screen('profile').update_display_name(updated_display_name.text); root.dismiss()