2016-07-24 92 views
1

我有一个简单的应用程序,要求您在TextInput字段中输入姓名和年龄。 当您单击保存按钮时,将打开一个Popup,您可以将名称和年龄从TextInput保存到文件中。Kivy从Popup获取TextInput

问题: 如何在Popup已打开时访问名称和年龄? 现在,我在打开Popup之前将TextInput数据存储在字典中。 此解决方案的工作,但也肯定是一个更优雅的解决方案莫过于:

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() 

回答

2

同比可以将对象传递给弹出对象。这样你就可以评估弹出对象的所有小部件属性。 这个例子可以看起来像这样。

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() 
+1

是否有办法做到倒退从弹出窗口获取数据并在主应用程序中访问它? – user2067030

+0

@ user2067030是在主窗口小部件类中,'self.save_popup'是弹出对象。所以你可以通过调用它的属性'self.save_popup.whatever_data_you_save_in_there'来访问它的数据 – EL3PHANTEN