gpt4 book ai didi

python - Kivy:如何在Python中引用kv ID?

转载 作者:行者123 更新时间:2023-12-01 02:24:56 25 4
gpt4 key购买 nike

我是 Kivy 的新手,我不得不认为这是可能的,但我无法弄清楚 - 如何在按下按钮时更新 Kivy 标签,但只能通过在 Python 中引用 Kivy id ? (我尝试这样做的原因是因为在我的实际应用程序中,我希望一次更新多个标签,我希望我可以在我的 button_pressed 等效按钮中完成所有操作我的应用程序中有)。

在下面的简单示例中,我只是尝试按下按钮,然后将标签更新为“已更新!”

非常感谢!

我的Python代码:

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.widget import Widget
from kivy.properties import StringProperty
import random


class TestingWidget(BoxLayout):

# This is the kv id of the Label I would like to update
label_to_update = StringProperty('')

# This is the action I would like to happen when the button is pressed
def button_pressed(self):
label_to_update.text = 'Updated!'

class TestButtonApp(App):
def build(self):
return TestingWidget()

if __name__ == '__main__':
TestButtonApp().run()

我的 kv 文件:

<TestingWidget>:
BoxLayout:
orientation: 'horizontal'
Button:
text: 'test'
on_press: root.button_pressed()
Label:
id: label_to_update
text: 'Trying to get this to update'

最佳答案

当您按下按钮时,您肯定会更新所有标签。只需为每个属性创建一个 StringProperty 并执行您现在正在执行的操作即可。

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.widget import Widget
from kivy.properties import StringProperty
from kivy.lang import Builder #used because I didn't want to create two files

import random

Builder.load_string('''
<TestingWidget>:
BoxLayout:
orientation: 'horizontal'
Button:
text: 'test'
on_press: root.button_pressed()
Label:
id: label_to_update
text: root.label_to_update
''')
class TestingWidget(BoxLayout):

# This is the kv id of the Label I would like to update
label_to_update = StringProperty('Trying to get this to update')
#default text set
# This is the action I would like to happen when the button is pressed
def button_pressed(self):
self.label_to_update = 'Updated!'

class TestButtonApp(App):
def build(self):
return TestingWidget()

if __name__ == '__main__':
TestButtonApp().run()

关于python - Kivy:如何在Python中引用kv ID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47503913/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com