如何通过绑定 class 使按钮改变颜色

How to make a button change colors by binding in a class

我尝试使用bind来绑定鼠标点击根据按钮的前景和背景改变颜色

from tkinter import *


class Clicks():
    def __init__(self, master):
        frame=Frame(master)
        frame.pack()

        #trying to bind the mouse clicks to change the color of the button

        self.button1= Button(frame, text="Click Me!", fg='red', bg='black')

        self.button1.bind("<Button-1>", fg='black')
        self.button1.bind("<Button-3>", bg='red')
        self.button1.grid(row = 0, column = 1, sticky = W)


root = Tk()
b = Clicks(root)
root.mainloop()

TypeError: bind() 得到了一个意外的关键字参数 'fg'

请检查代码段。您可以在此处使用 2 种方法。

首先你可以bind使用lambda函数

from tkinter import *
class Clicks():
    def __init__(self, master):
        frame=Frame(master)
        frame.pack()
        self.button1= Button(frame, text="Click Me!", fg='red', bg='black')
        self.button1.bind("<Button-1>", lambda event, b=self.button1: b.configure(bg="green",fg="blue"))
        self.button1.grid(row = 0, column = 1, sticky = W)
root = Tk()
b = Clicks(root)
root.mainloop()

其次,您可以通过传递 command 来访问函数

from tkinter import *
class Clicks():
    def __init__(self, master):
        frame=Frame(master)
        frame.pack()
        self.button1= Button(frame, text="Click Me!",command=self.color, fg='red', bg='black')
        self.button1.grid(row = 0, column = 1, sticky = W)
    def color(self):
        self.button1.configure(bg = "green",fg="blue")
root = Tk()
b = Clicks(root)
root.mainloop()