2017-09-04 73 views
0

我正在製作一個基於文本的遊戲,遊戲要求用戶輸入他們的姓氏。我已經制定了一種將名稱保存到文件並從文件中加載名稱的方法,但我不知道如何將輸入的文本保存到變量中。我嘗試了各種網上看到的方法,但到目前爲止還沒有一種方法可以爲我工作。我的代碼有問題的部分目前看起來是這樣的:(忽略奇的名字,如customwidget,我嘗試了一次,並給他們留下這樣的:P)將文本輸入保存到一個kivy應用程序的變量中

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

這將創建一個這樣的畫面:

但是,每當我將姓氏值保存到文件或嘗試打印姓氏時,它什麼都沒有。如果我能在這個問題上得到一些幫助,將不勝感激。在此先感謝您的幫助:)

+0

這工作對我很好,你如何試圖打印/保存到文件? –

回答

0

您必須聲明姓氏爲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

+0

我認爲最重要的變化是'surname'前面的'self'。使它成爲一個StringProperty肯定是一個好主意,但不是絕對必要的。 – syntonym

+0

似乎缺乏'StringProperty'和'self'是問題。我在使用整數值時碰巧使用'self',但是我也沒有將它用於文本變量。謝謝您的幫助 :) – Baller37

相關問題