I am writing a tkinter app in python 3.12.0 (on windows) and I want to bind the other "Enter" (Which is in Num-Lock part of keyboard) that when I press it, send my message. I am using a Text Widget and I need the main Enter for break line. I hove solved my problem with beneath code and it works on my system; But I'm looking for a better solution and I don't know if this function works on other systems or even if it works on a different OS.
def foo(event=None):
if not (event.keysym=="Return" and event.state in [
262144, # Caps Lock Off, Num Lock Off, Scroll Lock Off
262146, # Caps Lock On , Num Lock Off, Scroll Lock Off
262152, # Caps Lock Off, Num Lock On , Scroll Lock Off
262154, # Caps Lock On , Num Lock On , Scroll Lock Off
262176, # Caps Lock Off, Num Lock Off, Scroll Lock On
262178, # Caps Lock On , Num Lock Off, Scroll Lock On
262184, # Caps Lock Off, Num Lock On , Scroll Lock On
262186, # Caps Lock On , Num Lock On , Scroll Lock On
]):
return
# do the code
My problem is already solved. I just want to know is there a better way to bind the other "Enter"?
Edit: As I told in the first place: I want to use only the second Enter button and I think I couldn't get my point across.
Here is my code:
import tkinter as tk
def foo(event=None):
print(event)
print(event.state)
# to bind only to other Enter, but not the main Enter:
if event!=None and (not (event.keysym=="Return" and event.state in [
262144, # Caps Lock Off, Num Lock Off, Scroll Lock Off
262146, # Caps Lock On , Num Lock Off, Scroll Lock Off
262152, # Caps Lock Off, Num Lock On , Scroll Lock Off
262154, # Caps Lock On , Num Lock On , Scroll Lock Off
262176, # Caps Lock Off, Num Lock Off, Scroll Lock On
262178, # Caps Lock On , Num Lock Off, Scroll Lock On
262184, # Caps Lock Off, Num Lock On , Scroll Lock On
262186, # Caps Lock On , Num Lock On , Scroll Lock On
])):
return
print("Yey!")
root = tk.Tk()
text = tk.Text(root, width=60, height=8)
text.bind('<Key>', foo)
text.pack()
tk.Button(root, text='Send', command=foo).pack()
root.mainloop()
Please check others' answers.
Try this:
def foo(event=None):
if event and (not (event.keysym == "Return" and (event.state & 262144))):
return
print("Yey!")
However, if you press the keypad Enter
along with additional keys such as shift
, ctrl
, alt
or others, printing will still occur.
If you want printing to happen when you only press keypad Enter
and don't press any additional keys (other than various locks), try this code:
def foo(event=None):
if event and (not (event.keysym == "Return" and (event.state & 524245) == 262144)):
return
print("Yey!")
Just recently I've found a third option: Try to use the bind on Extended-Return
:
def foo(event=None):
print("Yey!")
root = tk.Tk()
text = tk.Text(root, width=60, height=8)
text.bind('<Extended-Return>', foo)
…
Should give the same result as the first example.