Tkinter中的动画按钮



我想在Tkinter中制作动画按钮。按钮有一个命令,当它们被点击时,它们会变大或变小,这取决于是否有人点击了另一个按钮。

from tkinter import*
screen = Tk()
screen.geometry("500x500")

def Test_clicked():
Testing_Button.config(width=6)
Testing_Button2.config(width=5)
def Test2_clicked():
Testing_Button.config(width=5)
Testing_Button2.config(width=6)

Testing_Button = Button(width=5,height=5, command=Test_clicked)
Testing_Button.place(x=0,y=0)
Testing_Button2 = Button(width=5,height=5, command=Test2_clicked)
Testing_Button2.place(x=0,y=90)




screen.mainloop()

当我运行该文件时,一切都正常,但如果我添加更多的按钮,只会使我的代码更长、更混乱。我想知道是否存在类似";FocusIn";用于按钮而不是Entry。

由于您有n按钮,只需提供按钮的名称作为参数即可。只需在将lambda作为按钮的命令传递时包含它。如果实现了这一点,您的代码将如下所示:

from tkinter import*
screen = Tk()
screen.geometry("500x500")
prev_button = None 
def Test_clicked(button):
global prev_button 

button.config(width=6)
try:
prev_button.config(width=5)
prev_button = button
except:
prev_button = button
Testing_Button = Button(width=5,height=5, command=lambda: Test_clicked(Testing_Button))
Testing_Button.place(x=0,y=0)
Testing_Button2 = Button(width=5,height=5, command=lambda: Test_clicked(Testing_Button2))
Testing_Button2.place(x=0,y=90)
screen.mainloop()

此外,在您的代码中,您使用的是来自tkinter-import*,这是一个坏习惯。还包括运算符前后的空格(等号和其他(,以提高的可读性

最新更新