我正在使用Tkinter的“place”功能创建一些按钮。我希望当用户将鼠标悬停在它们上面时,它们显示为灰色,当光标离开时,它们又变回黑色。我可以通过显式地绑定它们来做到这一点,但我想用一个循环动态地绑定它们。我试图创建的循环位于代码的底部,但它不起作用。在
如果您想知道我在说什么,那么这段代码将在python中运行。在
我如何创建一个动态循环来完成这项工作?在
from tkinter import *
FONT_SIZE = 14 # Change this to change all font sizes in the program
root = Tk()
root.resizable(width=TRUE, height=TRUE)
root.geometry("800x600")
root.config(background="black")
# Labels
newGameButton = Label(root)
loadGameButton = Label(root)
optionsButton = Label(root)
exitButton = Label(root)
Labels = [newGameButton, loadGameButton, optionsButton, exitButton]
#Changes the background of buttons when you hover over them
def changeBGEnter(widget):
widget.config(background="gray")
#Changes the background of buttons when you stop hovering them
def changeBGLeave(widget):
widget.config(background="black")
# Explicit bindings, ugly
newGameButton.bind("<Enter>", lambda x: changeBGEnter(newGameButton))
newGameButton.bind("<Leave>", lambda x: changeBGLeave(newGameButton))
loadGameButton.bind("<Enter>", lambda x: changeBGEnter(loadGameButton))
loadGameButton.bind("<Leave>", lambda x: changeBGLeave(loadGameButton))
optionsButton.bind("<Enter>", lambda x: changeBGEnter(optionsButton))
optionsButton.bind("<Leave>", lambda x: changeBGLeave(optionsButton))
exitButton.bind("<Enter>", lambda x: changeBGEnter(exitButton))
exitButton.bind("<Leave>", lambda x: changeBGLeave(exitButton))
# New Game Button
newGameButton.config(
anchor=CENTER, # Where to anchor the text in the widget
background="black",
foreground="white",
font=("default", FONT_SIZE),
text="NewGame",
)
newGameButton.place(
relwidth=0.6,
relheight=0.1,
relx=0.2,
rely=0.3
)
# Load Game Button
loadGameButton.config(
anchor=CENTER,
background="black",
foreground="white",
font=("default", FONT_SIZE),
text="Stats",
)
loadGameButton.place(
relwidth=0.6,
relheight=0.1,
relx=0.2,
rely=0.4
)
# Options Button
optionsButton.config(
anchor=CENTER,
background="black",
foreground="white",
font=("default", FONT_SIZE),
text="Output",
)
optionsButton.place(
relwidth=0.6,
relheight=0.1,
relx=0.2,
rely=0.5
)
# Exit Button
exitButton.config(
anchor=CENTER,
background="black",
foreground="white",
font=("default", FONT_SIZE),
text="Exit",
)
exitButton.place(
relwidth=0.6,
relheight=0.1,
relx=0.2,
rely=0.6
)
#Code I want that doesn't work:
#Get rid of explicit bindings above to test the code below
"""
for x in Labels:
x.bind("<Enter>", lambda x: changeBGEnter(x))
x.bind("<Leave>", lambda x: changeBGLeave(x))
"""
root.mainloop()
绑定send
event data
作为lambda
中的第一个参数,所以x
是event data
,而不是标签。(在
来复制它for
循环中)lambda不会将值从lab
复制到changeBGEnter(lab)
(而是使用lab
作为引用,changeBGEnter
的最后一个标签都相同),因此必须使用label=lab
一。在
-
(顺便说一句:您可以创建自己的小部件来简化它)
编辑:自己的小部件}
^{pr2}$MyButton
,绑定<Enter>
和{编辑:但是您可以使用
tkinter.Button
来获得相同的结果,而不需要自己的小部件或循环。在您可以使用
command=
将函数分配给按钮单击。在相关问题 更多 >
编程相关推荐