【发布时间】:2020-08-18 15:40:33
【问题描述】:
我正在尝试找出如何使 enter 键的行为与 tkinter 中的空格键相同。 到目前为止,唯一出现的是将回车键绑定到一个按钮。它的功能,到目前为止一切都很好。
但是:在视觉上它们并不相同。当您按下空格键时,按钮的浮雕会瞬间变为 SUNKEN。键绑定或调用 invoke() 没有相同的视觉效果。
在尝试寻找答案时,我可能发现了一个错误。当使用空格键按下按钮 5-10 秒时,RELIEF 将永久更改为 SUNKEN。不管你等多久。所以,这是我需要解决方法的另一件事。也许在函数调用重置按钮的状态之后......我会试试的。
以下是无法按预期工作的示例代码:
import tkinter as tk
root = tk.Tk()
root.geometry("300x200")
# if you press the enter key, buttons will call their own invoke function
# yet they won't show the effect of pressing space or clicking a button.
# When you press space or click a button the RELIEF will get changed.
# HOWEVER: When you hold space, the relief will get changed to SUNKEN permanently.
# That might me a bug.
root.bind_class("Button", "<Key-Return>", lambda event: event.widget.invoke())
def onclick():
print("You clicked the button")
button = tk.Button(root, text="click me", command=onclick)
button.pack()
# it's not a callback issue that the button remains SUNKEN after holding space for a bit.
button2 = tk.Button(root, text="this button has no command")
button2.pack()
root.mainloop()
编辑:我在 win10 上。
【问题讨论】:
-
我无法在 OSX 上重现
-
尝试将
event.widget.invoke()更改为event.widget.event_generate('<space>')。 -
这就像一个魅力!和一个绝妙的解决方案。这基本上是:当你按回车时,你按空格。
标签: python button tkinter binding widget