【发布时间】:2021-04-04 03:58:40
【问题描述】:
我正在尝试为不同的帧编写一个具有不同键绑定的程序。
如果框架被聚焦,这很好,但如果另一个小部件被聚焦,键绑定不起作用。
例如,在这个试验代码中,如果没有小部件处于焦点,则键绑定将起作用,但如果按钮被置于焦点(以编程方式或通过使用 TAB wkey 使按钮聚焦),则键绑定在框架上不再起作用。在按钮小部件上设置焦点后,将焦点设置在框架上并没有帮助。
import tkinter as tk
class TestGUI(tk.Frame):
def __init__(self, parent):
super().__init__(parent)
self.edit_text = tk.StringVar()
self.intro_label = tk.Label(self, text="Press button to say Hello")
self.hello_button = tk.Button(self, text='Say Hello (H)', command=self.press_button)
self.text_area = tk.Label(self, textvariable=self.edit_text, width=20, height=5)
self.intro_label.pack(padx=10, pady=5)
self.hello_button.pack(pady=5)
self.text_area.pack(padx=10, pady=(5, 10))
self.bind('<Key>', self.press_key)
self.hello_button.focus()
self.focus()
def press_button(self):
txt = self.edit_text.get()
txt += "Hello World!\n"
self.edit_text.set(txt)
def press_key(self, event):
key_pressed = event.char.lower()
if key_pressed == "h":
self.hello_button.invoke()
if __name__ == "__main__":
root = tk.Tk()
TestGUI(root).pack()
root.mainloop()
我知道如果我将绑定放在应用程序级别,键绑定仍然有效:
parent.bind('<Key>', self.press_key)
但是,我想在应用程序的不同框架上使用不同的键绑定。如果另一个小部件获得焦点,有没有办法做到这一点,而不会丢失键绑定?
【问题讨论】:
标签: python tkinter frame key-bindings