2016-07-24 20 views
1

TextInputフィールドにあなたの名前と年齢を尋ねる簡単なアプリがあります。 保存ボタンをクリックするとPopupが開き、TextInputの名前と年齢をファイルに保存できます。Kivyが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

関連する問題