python - Kivy:如何更改模板中 TextInput 的 text_hint 值
问题描述
我试图通过更改 TextInput 的 text_hint 值来显示一些数据。如果我打印它们是正确的值但是我不能让它们在屏幕上更新。这是我在 .kv 文件中声明和使用模板的方式。
<InformationBox@FloatLayout>
lblTxtIn: 'Unknown Variable Name'
txtInHint: "..."
Label:
text: root.lblTxtIn
color: 235/255, 235/255, 235/255, 1
pos_hint: {'center_x': 0.5, 'center_y': 0.7}
bold: True
TextInput:
readonly: True
hint_text: root.txtInHint
multiline: False
pos_hint: {'center_x': 0.5, 'center_y': 0.4}
size_hint: (0.3, 0.25)
hint_text_color: 0, 0, 0, 1
<MainMenu>:
InformationBox:
id: mylabel
lblTxtIn: "Data Type Name"
txtInHint: root.custom
这就是我尝试更改python中的值的方法。
from kivy.app import App
from kivy.uix.floatlayout import FloatLayout
from kivy.clock import Clock
from kivy.properties import ObjectProperty, StringProperty
import random
class MainMenu(FloatLayout):
custom = "0"
class MyMainApp(App):
def build(self):
return MainMenu()
def txt_change(self, *args):
MainMenu.custom = str(random.randrange(1, 10))
print(MainMenu.custom)
Clock.schedule_interval(txt_change, 1)
if __name__ == "__main__":
MyMainApp().run()
我也尝试使用 ObjectProperty 更改它,尽管它显示一个错误,告诉该对象没有“text_hint”属性。
class MainMenu(FloatLayout):
mylabel = ObjectProperty()
def change_text(self, *args):
MainMenu.mylabel.text_hint = "1"
class MyMainApp(App):
def build(self):
return MainMenu()
Clock.schedule_interval(MainMenu.change_text, 1)
我是一个初学者,不知道我是在犯一个简单的错误还是应该以完全不同的方式解决这个问题。如果有人可以帮助我,我会很高兴。
解决方案
您可以使用以下方法来更新 textinput 字段:
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.floatlayout import FloatLayout
from kivy.clock import Clock
import random
APP_KV = """
FloatLayout:
lblTxtIn: "Data Type Name"
txtInHint: "..."
Label:
text: root.lblTxtIn
color: 235/255, 235/255, 235/255, 1
pos_hint: {'center_x': 0.5, 'center_y': 0.7}
bold: True
TextInput:
id: mytxtinput
readonly: True
hint_text: root.txtInHint
multiline: False
pos_hint: {'center_x': 0.5, 'center_y': 0.4}
size_hint: (0.3, 0.25)
hint_text_color: 0, 0, 0, 1
"""
class MyMainApp(App):
def build(self):
return Builder.load_string(APP_KV)
def txt_change(self, *args):
app.root.ids.mytxtinput.hint_text = str(random.randrange(1, 10))
print(app.root.ids.mytxtinput.hint_text)
Clock.schedule_interval(txt_change, 1)
if __name__ == "__main__":
app = MyMainApp()
app.run()
推荐阅读
- python - 8 拼图游戏。如何检查和更改代表游戏板图块的目录键值
- node.js - 如何使用 tilda~ 从命令行安装 npm 包?
- erlang - 如何编译包含来自 erl shell 的 Erlang 文件?
- google-app-engine - Google App Engine 网址格式改为显示默认服务
- vue.js - 如何在 Vue 3 的 Composition API 中对反应性嵌套对象使用 .value?
- sql-server - 使用 Python 将 .xls DataFrame 插入 SQL 表
- css - 您可以从 git/shared 驱动器访问 css 文件以供公司共享使用吗?
- azure-api-management - Azure API 管理开发人员门户中的 API 特定页面
- php - PHP文件格式上传
- javascript - Intersectionobserver 和 InnerHTML 的无限滚动