尝试切换标签图像的Python GUI按钮

时间:2014-01-04 20:47:18

标签: python tkinter

我创建了一个带有切换按钮的GUI,用于切换按钮文本LED ON,LED OFF。我现在添加了一个带有图像的标签,我想尝试在按下按钮时切换标签图像。

我查了一些例子,但我不知道如何或在哪里添加代码以使标签图像切换。我尝试使用label.config将一段代码添加到我的IF语句的第一部分,但我尝试了我在论坛上阅读的内容,但最终它没有用。所以我来征求意见。

我得到的错误是...... AttributeError:'NoneType'对象没有属性'config'......我不明白。

感谢您的帮助。

我的代码......

# Idle 07_02_LED ON using GUI
from time import sleep

from Tkinter import *

class App:

    def __init__(self, master): 
            frame = Frame(master)
            frame.pack()
            Label(frame, text='Turn LED ON').grid(row=0, column=0)
            Label(frame, text='Turn LED OFF').grid(row=1, column=0)

            self.button = Button(frame, text='LED 0 ON', command=self.convert0)
            self.button.grid(row=2, column=0)

            self.LED = Label(frame, image=logo).grid(row=2, column=1)

    def convert0(self, tog=[0]):

        tog[0] = not tog[0]
        if tog[0]:
            print('LED 0 OFF')
            self.button.config(text='LED 0 OFF')
            self.LED.config(image = logo2)
        else:
            print('LED 0 ON')
            self.button.config(text='LED 0 ON')
            self.LED.config(image = logo)


root = Tk()
logo = PhotoImage(file="C:\My Documents\MyPictures\Green LED.gif")
logo2 = PhotoImage(file="C:\My Documents\My Pictures\Red LED.gif")

root.wm_title('LED on & off program')
app = App(root)
root.mainloop()

1 个答案:

答案 0 :(得分:1)

在阅读了更多帖子后,尤其是@Nick Meharry回答的帖子后,我发现我必须将以下一行分成两部分。

self.LED =标签(frame,image = logo).grid(row = 2,column = 1)

如果我这样做就行了......

self.LED =标签(frame,image = logo)

self.LED.grid(row = 2,column = 1)

通过greyskull的力量,它有效!

相关问题