python - Tkinter 与 Python 3.3 : Change colour of button on click

标签 python python-3.x tkinter

所以我一直在玩 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/

相关文章:

Python - 对 numpy.random 函数的调用线程安全吗?

python - 检查多个函数参数的优雅方法

Python - 检查正在使用哪个子类

python - 检查用 Selenium 打开的浏览器是否仍在运行(Python)

Python tkinter : How do I 'send' to a tkname that has spaces in it

python - Mamp 改变了我的 Python 之路

Python比较两个数据帧的列并生成匹配行的索引

python - 如何输入 float 和/或整数的numpy数组

python - 放置额外的 low_cost_node = None 来进行变量声明

python-3.x - python 3 散点图给出 "ValueError: Masked arrays must be 1-D"即使我没有使用任何掩码数组