Python Tkinter标签小部件鼠标悬停 [英] Python tkinter label widget mouse over

查看:1074
本文介绍了Python Tkinter标签小部件鼠标悬停的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的目标是当鼠标移到标签上时更改标签小部件的文本.对于一个标签,我将执行以下操作:

My objective is to change the text of label widget when the mouse move over the label.For one label i would do something like this:

import Tkinter as tk

def fun1(event):
    label.config(text="Haha")
def fun2(event):
    label.config(text="Label1")

root=tk.Tk()
label=tk.Label(root,text="Label1")
label.grid(row=1,column=1)
label.bind("<Enter>", fun1)
label.bind("<Leave>", fun2)
root.mainloop()

但是现在,我有一堆由for循环生成的标签和一个包含要更改的文本的列表.

But now, i have a bunch of labels which is generated by for loop and a list which contains the text that i want to change.

mylist=['a','b','c','d','e']
for i in range(5):
    tk.Label(root,text="Label"+str(i)).grid(row=i+1,column=1)

这将生成5个带有数字的标签.是否可以为每个单独的标签添加鼠标悬停事件,以便当我将鼠标悬停在标签1上时更改为"a",当我将鼠标悬停在标签2上时更改为"b",依此类推?仅供参考,我列表中的项目数始终与for循环中使用的项目数相同.

This will generate 5 labels with numbers. Is it possible to add mouse over event for each individual label so that when i mouse over on the label 1, it changes to 'a', when i mouse over to label 2, it changes to 'b', etc? FYI, the number of items in the mylist will always be the same with the number used in for loop.

推荐答案

import Tkinter as tk

root = tk.Tk()
mylist = ['a','b','c','d','e']

for i, x in enumerate(mylist):
    label = tk.Label(root, text="Label "+str(i))
    label.grid(row=i+1, column=1)
    label.bind("<Enter>", lambda e, x=x: e.widget.config(text=x))
    label.bind("<Leave>", lambda e, i=i: e.widget.config(text="Label "+str(i)))

root.mainloop()

这篇关于Python Tkinter标签小部件鼠标悬停的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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