[英]Are keyboard library and tkinter compatible?
我正在嘗試使用鍵盤上的箭頭鍵控制變量的值,以在 tkinter canvas 上實時移動一個正方形。我沒有錯誤消息,但是當我運行它 Python 3.11 時,彈出 canvas 但當我按下時沒有任何反應按鍵。 我在用着
from tkinter import *
from keyboard import *
tk=Tk()
tk.attributes('-fullscreen',True)
canvas=Canvas(tk, width=1366, height=768, background='#fff')
canvas.pack()
colors=[[(255, 255, 255) for i in range(223)] for i in range(321)]
def colr(lis):
a=lis[0]
b=lis[1]
c=lis[2]
if a%256<10:
va='0'+str(a%256)
else:
va=hex(a%256).replace('0x','')
if b%256<10:
vb='0'+str(b%256)
else:
vb=hex(b%256).replace('0x','')
if c%256<10:
vc='0'+str(c%256)
else:
vc=hex(c%256).replace('0x','')
return '#%s'%(va+vb+vc)
def fill_rect(a,b,c,d,e):
a=a+683
b=-b+384
if type(e)==str:
canvas.create_rectangle(a+2,b+2,c+a+2,d+b+2,fill=e,outline='')
else:
canvas.create_rectangle(a+2,b+2,c+a+2,d+b+2,fill=colr(e),outline='')
#Modify the value if the color at pixel x,y
for x in range(c):
for y in range(d):
if (a+x)>=0 and (a+x)<=320 and (b+y)>=0 and (b+y)<=222:
colors[a+x][b+y]=e
xinc=0
yinc=0
fill_rect(xinc,yinc,10,10,[0,0,0])
while True:
if is_pressed("left arrow")==True:
xinc=xinc-1
fill_rect(xinc,yinc,10,10,[0,0,0])
if is_pressed("right arrow")==True:
xinc=xinc+1
fill_rect(xinc,yinc,10,10,[0,0,0])
if is_pressed("up arrow")==True:
yinc=yinc+1
fill_rect(xinc,yinc,10,10,[0,0,0])
if is_pressed("down arrow")==True:
yinc=yinc-1
fill_rect(xinc,yinc,10,10,[0,0,0])
我真的不知道“is_pressed()”是如何工作的,所以它可能不是好的 function 甚至不是正確的庫,所以如果你推薦另一個,我會很樂意接受建議。
使用 tkinter 的內置事件綁定可能會更輕松
所以不要檢查像
if is_pressed("left arrow")==True:
xinc = xinc-1
fill_rect(xinc, yinc, 10, 10, [0,0,0])
你會寫類似的東西
def handle_event(event):
global xinc
global yinc
rect_props = (xinc,yinc,10,10,[0,0,0]) # no sense in repeating this...
if event.keysym == 'Left':
xinc=xinc-1
fill_rect(*rect_props)
elif event.keysym == 'Right':
xinc=xinc+1
fill_rect(*rect_props)
elif event.keysym == 'Up':
yinc=yinc+1
fill_rect(*rect_props)
elif event.keysym == 'Down':
yinc=yinc-1
fill_rect(*rect_props)
# bind the keyboard events to your root window
# you could also bind them to the canvas: 'canvas.bind(...)'
tk.bind('<Left>', handle_event)
tk.bind('<Right>', handle_event)
tk.bind('<Up>', handle_event)
tk.bind('<Down>', handle_event)
編寫 tkinter 時不應使用keyboard
模塊。Tkinter 會為您處理所有鍵盤事件。
在 tkinter 中處理鍵盤事件的方式是創建應在按下鍵時調用的函數。 然后,您可以將該 function 綁定到鍵盤事件。
例如,在您的代碼中,您可以創建如下所示的 function:
def left_arrow(event):
global xinc
xinc=xinc-1
fill_rect(xinc,yinc,10,10,[0,0,0])
然后,您可以將該 function 綁定到 canvas 上的<Left>
事件以調用 function:
canvas.bind("<Left>", left_arrow)
您還必須確保為 canvas 提供鍵盤焦點,因為默認情況下它不會獲得焦點。
canvas.focus_set()
這不是唯一的解決方案。 您還可以將所有鍵綁定到同一個 function,並檢查傳入的event
object 以查看按下了哪個鍵。 您還可以綁定到根 window 或所有 windows(如果您有多個)。
在 tkinter 中有更多關於事件處理的知識,它在大多數 tkinter 教程中都有介紹,例如tkdocs.com中的教程。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.