在tkinter中的标签上显示相应的消息

时间:2016-12-06 00:30:31

标签: python tkinter

- 编辑:我目前的尝试,非常难看

public static String perm(String word){

    char[] perm = new char[word.length()];
    char[] wordArray = word.toCharArray();
    char[] sortedWord = new char[word.length()];

    sortedWord = word.toCharArray();
    Arrays.sort(sortedWord);

    for (int i=0; i<word.length(); i++){
        for (int j=0; j<word.length(); j++){

            if (sortedWord[i] == wordArray[j]){
                perm[j] = (char)(65+i);  //from A
                wordArray[j] = '.';

                j = word.length();    //in case, if the word has more of the tested char, we jump to the end of the cycle
            }
        }
    }

    return String.valueOf(perm);
}

public static void main (String [] args){
    System.out.println(perm("alphabet"));
}

我想创建一组标签,比如说L1,L2,L3,每一个都有一个相应的标签La,Lb,Lc。我想要做的是当我将鼠标悬停在L1上时,La会在L1上显示单词的翻译。目前我正在查看Display message when going over something with mouse cursor in PythonPython Tkinter: addressing Label widget created by for loop,但它们都没有解决绑定相应的方法问题。有没有办法在不创建三对不同方法的情况下实现这一目标?

谢谢!

1 个答案:

答案 0 :(得分:1)

将每组标签存储在列表中。然后,您可以将它们与翻译词典一起浏览,并将辅助标签(显示翻译)连接到主标签(响应用户输入)。这允许您创建单个enter方法和单个leave方法,使用event.widget访问触发事件的窗口小部件。

import tkinter as tk

class Example(tk.Frame):
    def __init__(self, *args, **kwargs):
        tk.Frame.__init__(self, *args, **kwargs)
        self.translations = {'a':'A', 'b':'B', 'c':'C'}

        self.labelLists = [tk.Label(self,text=str(x),bg="red") for x in range(1,4)]
        self.labelBLists = [tk.Label(self,text="",bg="blue") for x in range(3)]
        for x,y,tr in zip(self.labelLists, self.labelBLists, sorted(self.translations)):
            x.bind('<Enter>', self.enter)
            x.bind('<Leave>', self.leave)
            x.connected = y
            x.key = tr
            x.pack()
            y.pack()

    def enter(self, event):
        widget = event.widget
        widget.connected.config(text=self.translations[widget.key])

    def leave(self, event):
        widget = event.widget
        widget.connected.config(text='')

if __name__ == "__main__":
    root = tk.Tk()
    Example(root).pack(side="top", fill="both", expand="true")
    root.mainloop()