简体   繁体   English

Python Tkinter标签小部件鼠标悬停

[英]Python tkinter label widget mouse over

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()

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. 但是现在,我有一堆由for循环生成的标签和一个包含要更改的文本的列表。

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

This will generate 5 labels with numbers. 这将生成5个带有数字的标签。 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? 是否可以为每个标签添加鼠标悬停事件,以便当我将鼠标悬停在标签1上时更改为“ a”,当我将鼠标悬停在标签2上时更改为“ b”,依此类推? FYI, the number of items in the mylist will always be the same with the number used in for loop. 仅供参考,mylist中的项目数将始终与for循环中使用的数相同。

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()

Event functions can be included in a class and strings for displaying can be defined by a constructor. 事件函数可以包含在类中,并且显示字符串可以由构造函数定义。

import Tkinter as tk

class Labels(object):
    def __init__(self,number,basicStr,onMouseStr):
        self.i = number
        self.basicStr = basicStr + str(number)
        self.onMouseStr = onMouseStr
        mylist=['a','b','c','d','e']
        self.label = tk.Label(root,text="Label"+str(i))
        self.label.grid(row=1+i,column=1)
        self.label.bind("<Enter>", self.fun1)
        self.label.bind("<Leave>", self.fun2)
    def fun1(self,event):
        self.label.config(text=self.basicStr)
    def fun2(self,event):
        self.label.config(text=self.onMouseStr)
root=tk.Tk()
labelsList = []
for i in range(5):
    lab = Labels(i,"haha","label"+str(i))
    labelsList.append(lab)
root.mainloop()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM