Reputation: 334
I'm trying to find out how I can make the enter key behave the same as the space key in tkinter. So far the only thing that came up was binding the enter key to a button. It functions, so far so good.
BUT: visually they aren't the same. When you press space, the relief of the button changes to SUNKEN for an instant. A key binding or calling invoke() doesn't have the same visual effect.
While trying to find an answer, I possibly found a bug. When pressing a button for like 5-10 seconds with the spacebar, the RELIEF gets changed to SUNKEN permanently. No matter how long you wait. So, that's another thing I need a workaround for. Maybe after the function call resetting the state of the button.... I'll try that.
Here's the sample code that doesn't work as expected:
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()
EDIT: I'm on win10.
Upvotes: 1
Views: 288
Reputation: 334
The solution @acw1668 posted works like a charm.
The code is now:
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()
It doesn't solve the sunken issue however.
Upvotes: 1