2016-07-24 52 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