Python tkinter label widget mouse over

此生再无相见时 提交于 2019-12-01 05:34:14

问题


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.

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. 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.


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/16665155/python-tkinter-label-widget-mouse-over

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!