[英]How to press a button when a specific character/number is pressed in keyboard on Python?
i have a simple calculator program that is running in a window with Tkinter that i called window = Tk()
, i have created normal buttons but i want that when i press for example "1" the bottun 1 is pressed, as if i clicked the button with the mouse.我有一个简单的计算器程序,它在 window 中运行,其中 Tkinter 我称为window = Tk()
,我创建了普通按钮,但我希望当我按下例如“1”时,按下 bottun 1,就好像我点击了用鼠标点击按钮。 So how can i detect if the specific number 1 is pressed?那么我如何检测是否按下了特定的数字 1 呢? Because for now the program prints "Hello" (it's for check that the character detection works) but with any letter/character i press, how to set a specific number for example "1"?因为现在程序打印“Hello”(这是为了检查字符检测是否有效)但是对于我按下的任何字母/字符,如何设置一个特定的数字,例如“1”? Thanks a lot and try to be clear i'm a beginner非常感谢,并尽量弄清楚我是初学者
bottone1= Button(window,text= "1", font= ('Helvetica 20 '),width=6,height=1,bg="#008BC7", command=lambda:button_press(1))
def var (e):
print("Hello")
window.bind("", var)
window.mainloop()
You can bind certain keys to a function that takes a *args
param - in case of the button press with your mouse the parameter will be None
- if you bind a key it will hold the keyevent:您可以将某些键绑定到带有*args
参数的 function - 如果用鼠标按下按钮,则参数将为None
- 如果您绑定一个键,它将保持键事件:
from tkinter import *
def pressMeFunc(*args):
if args:
print(args[0].char) # leverage the keyPressed event fields
else:
print("Hello")
window = Tk()
b = Button(window, text="Press Me", command=pressMeFunc)
b.pack()
window.bind("1", pressMeFunc)
window.bind("2", pressMeFunc)
window.bind("3", pressMeFunc)
window.mainloop()
If you start this and press the "2" key, you get in *args
a KeyPress event:如果您启动它并按下“2”键,您将在*args
中获得一个 KeyPress 事件:
You can use its .char
field to get the key pressed.您可以使用其.char
字段来按下按键。
You could create a dictionary with a "key" to "function" mapping and leverage that to call things depending on the key pressed:您可以创建一个带有“键”到“函数”映射的字典,并根据按下的键利用它来调用事物:
def one():
print("ONE")
def two():
print ("TWO")
def default_thing(*_):
print("Hello")
do_stuff_mapping = {"1": one, "2": two}
def pressMeFunc(*args):
if args:
print(args[0].char)
# get the function as defined above or default one
# if key is not mapped to a function - then call it
do_stuff_mapping.get(args[0].char, default_thing) ()
else:
default_thing(None)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.