请问一点帮助吗?我创建了一个带有切换按钮的GUI,用于切换按钮文本LED ON,LED OFF。我现在添加了一个带有图像的标签,我想尝试在按下按钮时切换标签图像。
我查了一些例子,但我不知道如何或在哪里添加代码以使标签图像切换。 我尝试使用label.config将一段代码添加到我的IF语句的第一部分,但我尝试了我在论坛上阅读的内容,但最终它没有用。所以我来征求意见。
感谢您的帮助。
我的代码......
# 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)
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')
LED = Label.config(image = logo2)
else:
print('LED 0 ON')
self.button.config(text='LED 0 ON')
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()
答案 0 :(得分:1)
将LED
替换为self.LED
。
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)
self.LED.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)