我试图找出如何使Enter键的行为与tkinter中的空格键相同。到目前为止,唯一出现的就是将Enter键绑定到按钮。到目前为止,它的功能还不错。
但是:在视觉上它们是不一样的。当您按下空格键时,按钮的释放会立即变为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上。
发布的解决方案@ acw1668就像是一种魅力。
现在的代码是:
import tkinter as tk
root = tk.Tk()
root.geometry("300x200")
# 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.event_generate("<space>"))
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()
但是它不能解决凹下去的问题。