python kivy kv模板调用,Kivy:如何在Python中引用kv ID?

I'm new to Kivy and I would have to think this is possible, but I can't figure it out - How can I update a Kivy label when a button is pressed, but only by referencing that Kivy id within Python? (The reason I'm trying to do it this way is because in my actual application, I would like several labels to update at once, which I was hoping I could do all within the button_pressed equivalent button I have in my app).

In the simple example below, I'm just trying to have the button pressed and then have the label update to 'Updated!'

Thanks very much!

My Python code:

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

My kv file:

:

BoxLayout:

orientation: 'horizontal'

Button:

text: 'test'

on_press: root.button_pressed()

Label:

id: label_to_update

text: 'Trying to get this to update'

解决方案

You definitely update all label when you press the button. Just crate a StringProperty for each and do what you are doing now.

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

:

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值