Python tkinter label widget mouse over

前端 未结 2 1750
我寻月下人不归
我寻月下人不归 2021-01-13 22:18

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         


        
相关标签:
2条回答
  • 2021-01-13 22:57
    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()
    
    0 讨论(0)
  • 2021-01-13 23:01

    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()
    
    0 讨论(0)
提交回复
热议问题