tkinter:动态更改标签文本而无需重复 If 测试

tkinter: Dynamically change label text without repetitive If testing

我希望与某些小部件名称关联的唯一消息在这些小部件获得焦点时显示为单个标签的文本。消息是字典中对应于字典键的值,字典键是与小部件名称相同的字符串。如图所示,如果我使用重复的 IF 语句来识别键并显示相应的值,这会起作用,但我想用一个函数替换将成为大量 IF 语句的内容,该函数无需重复即可执行相同的操作。我在 Javascript 中完成了此操作,但 and I don't understand coding well enough to translate the js to Python. I've been working on this for days and the 通过从组合框中获取条目选择来完成类似的操作。如果我有猜测组合框如何知道其中发生的事情的经验,这在理论上可能适用于我的情况。此外,如果不需要 textvariable 那么没有它如何做到这一点,但由于我是 "sharing the variable between two or more widgets"(根据 Bryan Oakley),我认为可能需要它。我什至可能需要两个文本变量?谢谢

import tkinter as tk
from tkinter import ttk

def clear(event):
    statusBar_value.set('')

def set_statusBar(event):
    w = widget_name
    focw = root.focus_get()
    if entry1==focw: 
        statusBar_value.set(w['entry1'])
    if entry2==focw:
        statusBar_value.set(w['entry2'])

root = tk.Tk()

statusBar_value = tk.StringVar()
statusBar_value.set('Status Bar...')

widget_name = {'entry1':'Entry 1 has focus', 'entry2':'Entry 2 has focus'}

entry1 = ttk.Entry(root)
dummy =  ttk.Entry(root)
entry2 = ttk.Entry(root)

statusBar = ttk.Label(root, textvariable = statusBar_value)

entry1.grid()
dummy.grid()
entry2.grid()

statusBar.grid()

entry1.bind('<FocusIn>', set_statusBar)
entry1.bind('<FocusOut>', clear)

entry2.bind('<FocusIn>', set_statusBar)
entry2.bind('<FocusOut>', clear)

root.mainloop()

一个简单的方法是让 Entry 小部件成为 widget_name 字典的键:

import tkinter as tk
from tkinter import ttk

def clear(event):
    statusBar_value.set('')

def set_statusBar(event):
    statusBar_value.set(widget_name[event.widget])

root = tk.Tk()

statusBar_value = tk.StringVar()
statusBar_value.set('Status Bar...')

entry1 = ttk.Entry(root)
dummy =  ttk.Entry(root)
entry2 = ttk.Entry(root)

widget_name = {entry1:'Entry 1 has focus', entry2:'Entry 2 has focus'}

statusBar = ttk.Label(root, textvariable = statusBar_value)

entry1.grid()
dummy.grid()
entry2.grid()

statusBar.grid()

entry1.bind('<FocusIn>', set_statusBar)
entry1.bind('<FocusOut>', clear)

entry2.bind('<FocusIn>', set_statusBar)
entry2.bind('<FocusOut>', clear)

root.mainloop()