使用 Python 3.3 的 Tkinter:单击时更改按钮的颜色 [英] Tkinter with Python 3.3 : Change colour of button on click

查看:63
本文介绍了使用 Python 3.3 的 Tkinter:单击时更改按钮的颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我一直在玩 tkinter,尝试将 gui 添加到我为大学编写的电梯模拟器项目中.它不是真的需要,但我想添加它.

So I have been playing with tkinter to try add a gui to a lift simulator project I have written for university. It is not really needed, but I would like to add it.

这是我目前拥有的代码.

Here is the code that I currently have.

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)的背景更改为红色,而不是按下的那个.

This is all fine and dandy other than when the button is pressed it prints out the correct number, but it changes the background of the last button (number 40) to red, not the one pressed.

如果您能告诉我哪些需要更正,那就太好了.

If you could let me know what needs correcting that would be great.

谢谢

推荐答案

self.button 只能引用一个按钮,而且它总是最后分配给它的任何东西.一个简单的解决方案是将按钮引用存储在字典中,使用 floor 作为键.由于您将其传递给回调,因此您拥有重新配置按钮所需的一切:

self.button can only ever reference a single button, and it will always be whatever was assigned to it last. A simple solution is to store the button references in a dict, using floor as the key. Since you're passing that to the callback, you then have everything you need to reconfigure the button:

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 3.3 的 Tkinter:单击时更改按钮的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆