所以我一直在玩 tkinter,尝试将图形用户界面添加到我为大学编写的电梯模拟器项目中。它不是真的需要,但我想添加它。
这是我目前拥有的代码。
import tkinter as tk
class Application(tk.Frame):
def __init__(self, master=None):
tk.Frame.__init__(self, master)
master.title("Test") #Controls the window title.
self.pack()
self.createWidgets()
def createWidgets(self):
floors = [i for i in range(41)]
buttons = []
xPos = 0
yPos = 0
for floor in floors:
if(yPos == 5):
xPos = xPos + 1
yPos = 0
if(xPos == 8):
yPos = 2
self.button = tk.Button(self, width=3, text=floor,
command = lambda f=floor: self.pressed(f))
self.button.grid(row=xPos, column =yPos)
yPos = yPos +1
self.QUIT = tk.Button(self, text="QUIT", fg="red",
command=root.destroy).grid(row = xPos, column = yPos)
def pressed(self, index):
print("number pressed", index)
self.button.configure(bg = "red")
root = tk.Tk()
app = Application(master=root)
app.mainloop()
除了按下按钮时它打印出正确的数字外,这一切都很好而且花花公子,但它将最后一个按钮(数字 40)的背景更改为红色,而不是按下的按钮。
如果您能让我知道需要更正的地方,那就太好了。
谢谢
最佳答案
self.button
只能引用一个按钮,并且它始终是最后分配给它的任何内容。一个简单的解决方案是将按钮引用存储在字典中,使用 floor
作为键。由于您将其传递给回调,因此您拥有了重新配置按钮所需的一切:
def createWidgets(self):
...
self.buttons = {}
for floor in floors:
...
self.buttons[floor] = tk.Button(...)
...
def pressed(self, index):
...
self.buttons[index].configure(bg="red")
关于python - Tkinter 与 Python 3.3 : Change colour of button on click,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20829890/