如何在Tkinter中悬停后更改多个小部件的颜色? [英] How to change colors of multiple widgets after hovering in Tkinter?

查看:263
本文介绍了如何在Tkinter中悬停后更改多个小部件的颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创建一个脚本,这将改变悬停后的窗口小部件的背景和前景色。

 来自Tkinter import * 

root = Tk()

Hover1 = button(root,text =Red color,bg =white)
Hover1.pack()

Hover2 = white)
Hover2.pack()

Hover1.bind(< Enter>,Hover1.configure(bg =red))
Hover1.bind (< Leave>,Hover1.configure(bg =white))

Hover2.bind(< Enter>,Hover2.configure(bg =yellow))
Hover2.bind(< Leave>,Hover2.configure(bg =white))

root.mainloop()
/ pre>

但是当我在任何按钮上悬停时,没有任何反应,他们保持白色。我知道我可以使用一个函数,但会有两个功能为每个小部件(1为,
1)。我想创建一个单一的函数,它会重新着色该小部件我悬停在上面,并解释为什么这个脚本不做我想要它做的。



我希望我能很好地描述我的问题。感谢每一个答案。



PS:我想避免课程。



mountDoom

解决方案

您需要提供一个可调用的函数来绑定到事件。相反,你调用一个函数并传递它的结果。修正它如下:

  Hover1.bind(< Enter>,lambda事件,h = Hover1:h.configure (bg =red))


I´m trying to make a script, which will change the background and foreground color of widgets after hovering.

from Tkinter import *

root=Tk()

Hover1=Button(root,text="Red color", bg="white")
Hover1.pack()

Hover2=Button(root,text="Yellow color", bg="white")
Hover2.pack()

Hover1.bind("<Enter>",Hover1.configure(bg="red"))
Hover1.bind("<Leave>",Hover1.configure(bg="white"))

Hover2.bind("<Enter>",Hover2.configure(bg="yellow"))
Hover2.bind("<Leave>",Hover2.configure(bg="white"))

root.mainloop()

but when I hover on any button, nothing happens, they stay white. I know I could use a function, but there would be two functions for every widget (1 for , 1 for ). I'd like to create a single function, which will recolor that widget I hover on and explain why this script is not doing what I want it to do.

I hope I described my problem well. Thanks for every answer.

PS: I would like to avoid classes.

mountDoom

解决方案

You need to provide a callable function to bind to the event. Instead you are calling a function and passing its result. Fix it like this:

Hover1.bind("<Enter>", lambda event, h=Hover1: h.configure(bg="red"))

这篇关于如何在Tkinter中悬停后更改多个小部件的颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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