[英]How to press a button when a specific character/number is pressed in keyboard on Python?
我有一個簡單的計算器程序,它在 window 中運行,其中 Tkinter 我稱為window = Tk()
,我創建了普通按鈕,但我希望當我按下例如“1”時,按下 bottun 1,就好像我點擊了用鼠標點擊按鈕。 那么我如何檢測是否按下了特定的數字 1 呢? 因為現在程序打印“Hello”(這是為了檢查字符檢測是否有效)但是對於我按下的任何字母/字符,如何設置一個特定的數字,例如“1”? 非常感謝,並盡量弄清楚我是初學者
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()
您可以將某些鍵綁定到帶有*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()
如果您啟動它並按下“2”鍵,您將在*args
中獲得一個 KeyPress 事件:
您可以使用其.char
字段來按下按鍵。
您可以創建一個帶有“鍵”到“函數”映射的字典,並根據按下的鍵利用它來調用事物:
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.