问题描述
我尝试使用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,command=self.color,bg='black')
self.button1.grid(row = 0,sticky = W)
def color(self):
self.button1.configure(bg = "green",fg="blue")
root = Tk()
b = Clicks(root)
root.mainloop()