我有一个简单的应用,可以在TextInput
字段中询问您的姓名和年龄。
当您点击保存按钮时,会打开Popup
,您可以将TextInput
中的姓名和年龄保存在文件中。
问题:
当Popup
已经打开时,如何访问姓名和年龄?
现在我在打开TextInput
之前将Popup
数据存储在字典中。
这种解决方法确实有效,但肯定是比这更优雅的解决方案:
class SaveDialog(Popup):
def redirect(self, path, filename):
RootWidget().saveJson(path, filename)
def cancel(self):
self.dismiss()
class RootWidget(Widget):
data = {}
def show_save(self):
self.data['name'] = self.ids.text_name.text
self.data['age'] = self.ids.text_age.text
SaveDialog().open()
def saveFile(self, path, filename):
with open(path + '/' + filename, 'w') as f:
json.dump(self.data, f)
SaveDialog().cancel()
答案 0 :(得分:2)
Yoy可以将您的对象传递给弹出对象。这样,您就可以为弹出对象提供所有窗口小部件属性。 这方面的一个例子可能是这样的。
from kivy.uix.popup import Popup
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
from kivy.uix.textinput import TextInput
from kivy.app import App
class MyWidget(BoxLayout):
def __init__(self,**kwargs):
super(MyWidget,self).__init__(**kwargs)
self.orientation = "vertical"
self.name_input = TextInput(text='name')
self.add_widget(self.name_input)
self.save_button = Button(text="Save")
self.save_button.bind(on_press=self.save)
self.save_popup = SaveDialog(self) # initiation of the popup, and self gets passed
self.add_widget(self.save_button)
def save(self,*args):
self.save_popup.open()
class SaveDialog(Popup):
def __init__(self,my_widget,**kwargs): # my_widget is now the object where popup was called from.
super(SaveDialog,self).__init__(**kwargs)
self.my_widget = my_widget
self.content = BoxLayout(orientation="horizontal")
self.save_button = Button(text='Save')
self.save_button.bind(on_press=self.save)
self.cancel_button = Button(text='Cancel')
self.cancel_button.bind(on_press=self.cancel)
self.content.add_widget(self.save_button)
self.content.add_widget(self.cancel_button)
def save(self,*args):
print "save %s" % self.my_widget.name_input.text # and you can access all of its attributes
#do some save stuff
self.dismiss()
def cancel(self,*args):
print "cancel"
self.dismiss()
class MyApp(App):
def build(self):
return MyWidget()
MyApp().run()