Kivy图像未显示在toggleButton内的网格布局中 - python

这是我的第一个Kivy GUI界面,因此我怀疑我没有正确执行某些操作。但是,我想知道为什么会这样或如何达到期望的结果。

我正在尝试在“切换按钮”中渲染图像。无论出于何种原因,在运行应用程序时仅加载第二个按钮。

我将引发问题的切换按钮涂成绿色,因此可以检查定位是否关闭。绑定到按钮的功能起作用,图像图标将完全不显示。

Kivy图像未显示在toggleButton内的网格布局中 - python

这是我的.kv文件:

<Controller>:
lbl: my_label
tbl: my_other_label
atl: attendant_label
timg: my_test_img
aimage: attendant_img

BoxLayout:
    canvas.before:
        Color:
            rgba: 0.137, 0.149, 0.161, 1
        Rectangle:
            # self here refers to the widget i.e BoxLayout
            pos: self.pos
            size: self.size
    orientation:'horizontal'

    GridLayout:
        cols:1
        rows:2

        ##THIS DOES NOT DISPLAY
        ToggleButton:
            id:attendant_label
            group: 'g2'
            border:0,0,0,0          
            background_color:(0, 1, 0, 1.0)
            background_normal:''
            background_down: ''
            on_press: root.attendantchange(*args)

            Image:
                id:attendant_img
                source: 'attendantoff.png'
                size: self.parent.width, self.parent.height
        ##THIS DISPLAYS..
        ToggleButton:
            id:my_other_label
            group: 'g1'
            border:0,0,0,0          
            background_color:(0.137, 0.149, 0.161, 1.0)
            background_normal:''
            background_down: ''
            on_press: root.buttonchange(*args)

            Image:
                id:my_test_img
                source: 'bulb1.png'
                size: self.parent.width, self.parent.height

    Slider:
        canvas:
            Color:
                rgb: 0.89,0.694,0
            BorderImage:
                border: (0, 18, 0, 18) if self.orientation == 'horizontal' else (18, 0, 18, 0)
                pos: (self.x + self.padding, self.center_y - sp(18)) if self.orientation == 'horizontal' else (self.center_x - 35, self.y + self.padding)
                size: (max(self.value_pos[0] - self.padding * 2 - sp(16), 0), sp(36)) if self.orientation == 'horizontal' else (sp(36), max(self.value_pos[1] - self.padding * 2, 0))
                source: 'atlas://data/images/defaulttheme/slider{}_background{}'.format(self.orientation[0], '_disabled' if self.disabled else '')
        id:my_label
        size_hint:.25,1
        min: 0
        max: 100
        enabled: False
        disabled: True
        orientation:'vertical'
        value_track_color: [0, 1, 0, 1]
        on_value: root.new_brightness(*args)

这是Python代码:

import paho.mqtt.client as mqtt

import kivy
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.gridlayout import GridLayout

kivy.require('1.10.1') # replace with your current kivy version !


class Controller(BoxLayout):

    def __init__(self):
        self.buttonState = 0;
        self.attendantState = 0;
        self.oldBrightness = '0';
        self.client = mqtt.Client();

        super(Controller,self).__init__()

    def new_brightness(self,*args):
        if(self.buttonState == 0):
            print('light is off');
        else:
            #self.lbl.text = str(int(args[1]))
            #self.tbl.text = str(int(args[1]))
            self.oldBrightness = str(int(args[1]))
            if(int(args[1]) <= 10):
                self.timg.source = "bulb2.png"
            elif (int(args[1]) <= 50):
                self.timg.source = "bulb2.png"
            else:
                self.timg.source = "bulb2.png"

            self.publish(self.oldBrightness)

    def buttonchange(self,*args):
        if(self.buttonState == 0):
            self.buttonState = 1;
            self.lbl.enabled = True;
            self.lbl.disabled = False;
            self.timg.source='bulb2.png'
            self.publish(1)
        else:
            self.buttonState = 0;
            self.timg.source='bulb1.png'
            self.lbl.enabled = False;
            self.lbl.disabled = True;
            self.publish(0)

        #self.tbl.text = str(self.buttonState)
        print(str(self.__class__) + ": " + str(self.__dict__))

    def attendantchange(self,*args):
        if(self.attendantState == 0):
            self.attendantState = 1;
            self.aimage.source='attendanton.png'
        else:
            self.attendantState = 0;
            self.aimage.source='attendantoff.png'

        print(str(self.__class__) + ": " + str(self.__dict__))

    def __str__(self):
        return str(self.__class__) + ": " + str(self.__dict__)

    def publish(self,value):
        # When I manually send a message from the command line, there is a connect, send, disconnect process
        #  I am recreating that process here as opposed to connecting once and leaving the connection open.
        #  If there is only a single connection attempt which fails because the receiver is powered off, etc
        #  that would leave us with no way to reestablish communications
        # connect to broker
        Broker = "192.168.1.21"
        pub_topic = "RL"
        #self.client.connect(Broker, 1883, 60)
        # I need this for message subscriptions; not sure about publising
        #self.client.loop_start()
        # send updated value to reading light
        #self.client.publish(pub_topic, value)
        # close everything down after sending a message
        #self.client.loop_stop()
        #self.client.disconnect()

class MyApp(App):

    def build(self):
        return Controller()

window = MyApp()
window.run()

参考方案

如果我了解您的要求,则可以简单地通过使用background_normalbackground_downToggleButton属性来实现。另外,ToggleButton不是容器,因此尝试将Image用作ToggleButton的子代并没有任何意义。因此,在您的Kivy文件中,尝试像这样设置ToggleButton

        ##THIS DOES NOT DISPLAY
        ToggleButton:
            id:attendant_label
            group: 'g2'
            border:0,0,0,0 
            background_normal:'attendantoff.png'
            background_down: 'attendanton.png'
            on_press: root.attendantchange(*args)

消除ImageToggleButton子级,并删除root.attendantchange()中试图更改Image的代码。对其他ToggleButton进行相同的更改。另外,请注意background_color中的ToggleButton只是对实际图像进行着色,因此您可能也希望将其删除。

在返回'Response'(Python)中传递多个参数 - python

我在Angular工作,正在使用Http请求和响应。是否可以在“响应”中发送多个参数。角度文件:this.http.get("api/agent/applicationaware").subscribe((data:any)... python文件:def get(request): ... return Response(seriali…

Python exchangelib在子文件夹中读取邮件 - python

我想从Outlook邮箱的子文件夹中读取邮件。Inbox ├──myfolder 我可以使用account.inbox.all()阅读收件箱,但我想阅读myfolder中的邮件我尝试了此页面folder部分中的内容,但无法正确完成https://pypi.python.org/pypi/exchangelib/ 参考方案 您需要首先掌握Folder的myfo…

python JSON对象必须是str,bytes或bytearray,而不是'dict - python

在Python 3中,要加载以前保存的json,如下所示:json.dumps(dictionary)输出是这样的{"('Hello',)": 6, "('Hi',)": 5}当我使用json.loads({"('Hello',)": 6,…

R'relaimpo'软件包的Python端口 - python

我需要计算Lindeman-Merenda-Gold(LMG)分数,以进行回归分析。我发现R语言的relaimpo包下有该文件。不幸的是,我对R没有任何经验。我检查了互联网,但找不到。这个程序包有python端口吗?如果不存在,是否可以通过python使用该包? python参考方案 最近,我遇到了pingouin库。

Python ThreadPoolExecutor抑制异常 - python

from concurrent.futures import ThreadPoolExecutor, wait, ALL_COMPLETED def div_zero(x): print('In div_zero') return x / 0 with ThreadPoolExecutor(max_workers=4) as execut…