我有一个简单的应用程序,可在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()

最佳答案

您可以将您的对象传递给弹出对象。这样,您可以访问弹出对象的所有窗口小部件属性。
这样的例子看起来像这样。

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

关于python - Kivy从弹出窗口获取TextInput,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38548075/

10-12 18:54