在 Kivy 应用程序中获取文本输入值
Posted
技术标签:
【中文标题】在 Kivy 应用程序中获取文本输入值【英文标题】:Get textinput value in Kivy app 【发布时间】:2014-12-06 12:16:24 【问题描述】:Python/Kivy 的新手尝试构建一个带有输入框、ok 按钮和一个标签的测试应用程序,该标签在单击 ok 按钮时应该更改文本。但相反,我得到'NameError:全局名称'txt1'未定义'。我做错了什么?
# import Kivy
import kivy
import random
from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.uix.textinput import TextInput
# my app
class MyApp(App):
# layout
def build(self):
layout = BoxLayout(padding=10, orientation='vertical')
btn1 = Button(text="OK")
btn1.bind(on_press=self.buttonClicked)
layout.add_widget(btn1)
lbl1 = Label(text="test")
layout.add_widget(lbl1)
txt1 = TextInput(text='', multiline=False)
layout.add_widget(txt1)
return layout
# button click function
def buttonClicked(self,btn):
lbl1.text = "You wrote " + txt1.text
# run app
if __name__ == "__main__":
MyApp().run()
【问题讨论】:
【参考方案1】:使用self.txt1, self.lbl1
等。
class MyApp(App):
# layout
def build(self):
layout = BoxLayout(padding=10, orientation='vertical')
btn1 = Button(text="OK")
btn1.bind(on_press=self.buttonClicked)
layout.add_widget(btn1)
self.lbl1 = Label(text="test")
layout.add_widget(self.lbl1)
self.txt1 = TextInput(text='', multiline=False)
layout.add_widget(self.txt1)
return layout
# button click function
def buttonClicked(self,btn):
self.lbl1.text = "You wrote " + self.txt1.text
# run app
if __name__ == "__main__":
MyApp().run()
# join all items in a list into 1 big string
使用:
def buttonClicked(self,btn):
lbl1.text = "You wrote " + txt1.text <- only exists in the build method
【讨论】:
在 KV 中你应该可以使用: TextInput: \n text: " " \n multiline: False以上是关于在 Kivy 应用程序中获取文本输入值的主要内容,如果未能解决你的问题,请参考以下文章