【问题标题】:How to pass a var from py to kv with click button?如何使用单击按钮将 var 从 py 传递到 kv?
【发布时间】:2021-02-12 03:30:30
【问题描述】:

喂。我有一个小代码:屏幕顶部有一个按钮,中间有一个圆圈。当您单击时,颜色应更改为交通灯颜色,但它不这样做。有人可以帮助我吗?谢谢!

image_test.py

import kivy
from kivy.app import App

from kivy.uix.floatlayout import FloatLayout
from kivy.uix.button import Button

light = 0

class myScreen(FloatLayout):

    def __init__(self, **kwargs):
        super(myScreen, self).__init__(**kwargs)
        self.img_src = 'images/traffic_light_red.png'

    def change_color(self):
        global light
        img = [
            'images/traffic_light_red.png',
            'images/traffic_light_yellow.png',
            'images/traffic_light_green.png'
            ]
        light += 1 
        if light > 2: light = 0
        self.img_src = img[light]
        print(light, self.img_src)

class myImageApp(App):
    def build(self): return myScreen()

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

myImage.kv

#:kivy 2.0.0
#:import AsyncImage kivy.uix.image.AsyncImage

<myScreen>:

    canvas.before:
        Color:
            rgba: (1.,1.,0.8,1.)
        Rectangle:
            pos: self.pos
            size: self.size

    Button:
        text: 'traffic light color'
        size_hint: [None, None]
        size: 200, 100
        pos_hint: {'center_x':.5, 'top':1}
        on_press: root.change_color()
    
    AsyncImage:
        source: 'images/traffic_light_red.png'

【问题讨论】:

    标签: python kivy kivy-language


    【解决方案1】:

    一个简单的方法是将id 添加到AsyncImage,如下所示:

    AsyncImage:
        id: img
        source: 'images/traffic_light_red.png'
    

    并在您的 change_color() 方法中使用它:

    def change_color(self):
        global light
        img = [
            'images/traffic_light_red.png',
            'images/traffic_light_yellow.png',
            'images/traffic_light_green.png'
            ]
        light += 1 
        if light > 2: light = 0
        self.ids.img.source = img[light]  # use `ids` to access the image
        print(light, self.img_src)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-30
      • 1970-01-01
      • 2014-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多