将文本输入保存到kivy应用程序中的变量

时间:2017-09-04 23:29:19

标签: python python-3.x kivy python-3.6

我正在制作一个基于文本的游戏,游戏要求用户输入他们的姓氏。我已经找到了一种方法来将名称保存到文件中,并从文件中加载名称,但我不知道如何保存已输入到变量中的文本。我尝试过在线看过的各种方法,但迄今为止没有一种方法对我有效。我的代码部分目前看起来像这样:(忽略奇怪的名字,比如customwidget,我正在尝试一次并将它们留下:P)

testing.py文件:

import kivy
kivy.require("1.9.0")
from kivy.properties import NumericProperty

from kivy.app import App
from kivy.uix.widget import Widget
from kivy.properties import ObjectProperty

class CustomWidget(Widget):
    last_name_text_input = ObjectProperty()
    ego = NumericProperty(0)
    surname = ''

    def submit_surname(self):
        surname = self.last_name_text_input.text

class CustomWidgetApp(App):
    def build(self):
        return CustomWidget()

customWidget = CustomWidgetApp()
customWidget.run()

customwidget.kv文件:

<CustomWidget>:
    last_name_text_input: last_name
    Label:
        text: "Last Name:"
        pos: 655,400
        size: 100, 30
    TextInput:
        id: last_name
        pos: 760,400
        size: 100, 30
    Button:
        text: "Save Name"
        pos: 870,400
        size: 100, 30
        on_release: root.submit_surname()

这会创建一个这样的屏幕:

但是,每当我将姓氏值保存到文件或尝试打印姓氏时,它都没有任何结果。如果我能在这个问题上得到一些帮助,我将不胜感激。在此先感谢您的任何帮助:)

1 个答案:

答案 0 :(得分:1)

您必须将姓氏声明为StringProperty。请参考下面的示例。

main.py

    from kivy.app import App
    from kivy.uix.widget import Widget
    from kivy.properties import ObjectProperty, NumericProperty, StringProperty


    class CustomWidget(Widget):
        last_name_text_input = ObjectProperty()
        ego = NumericProperty(0)
        surname = StringProperty('')

        def submit_surname(self):
            self.surname = self.last_name_text_input.text
            print("Assign surname: {}".format(self.surname))
            self.save()
            self.surname = ''
            print("Reset surname: {}".format(self.surname))
            self.load()
            print("Loaded surname: {}".format(self.surname))

        def save(self):
            with open("surname.txt", "w") as fobj:
                fobj.write(str(self.surname))

        def load(self):
            with open("surname.txt") as fobj:
                for surname in fobj:
                    self.surname = surname.rstrip()


    class CustomWidgetApp(App):
        def build(self):
            return CustomWidget()

if __name__ == "__main__":
    CustomWidgetApp().run()

customwidget.kv

#:kivy 1.10.0

<CustomWidget>:
    last_name_text_input: last_name
    Label:
        text: "Last Name:"
        pos: 655,400
        size: 100, 30
    TextInput:
        id: last_name
        pos: 760,400
        size: 100, 30
    Button:
        text: "Save Name"
        pos: 870,400
        size: 100, 30
        on_release: root.submit_surname()

输出

enter image description here