Kivy从弹出窗口获取文本输入

2024-05-16 02:06:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个简单的应用程序,它在TextInput字段中询问您的姓名和年龄。 当您单击save按钮时,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()

Tags: pathtextselfdatasavedeftextinputfilename
1条回答
网友
1楼 · 发布于 2024-05-16 02:06:54

你可以把你的对象传递给弹出对象。这样您就可以访问弹出对象的所有小部件属性。 一个例子可以是这样的。在

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

相关问题 更多 >