2016-11-27 95 views
1

所以我做小泛出的Tkinter做作的比賽,我面臨wall.Compiler只抓住了一個關鍵事件,如果第二用戶按下按鍵,1用戶運動LL停止。你們知道如何解決這個問題嗎?如何捕捉兩個關鍵事件的Tkinter

這裏是代碼:

from tkinter import* 
w=600 
h=300 
padis_sigane=10 
padis_sigrdze=75 
padis_sichqare=5 
root=Tk() 
root.geometry("{}x{}".format(w,h)) 
root.resizable(False,False) 
c=Canvas(root,width=w,height=h,bg="green") 
c.create_line(w//2,0,w//2,h,width=10,fill="white") 
c.create_line(padis_sigane,0,padis_sigane,h,width=2,fill="white") 
c.create_line(w-padis_sigane,0,w-padis_sigane,h,width=2,fill="white") 
c.create_oval(w//2-w//30,h//2-w//30,w//2+w//30,h//2+w//30,fill="white",outline="white") 
class chogani: 
    def __init__(self,x,y): 
     self.x=x 
     self.y=y 
     self.pad=c.create_rectangle(self.x,self.y,self.x+padis_sigane,self.y+padis_sigrdze,fill="lightblue",outline="white") 
    def shxuili(self): 

     if c.coords(self.pad)[3]>=h: 
      c.coords(self.pad,self.x,h-padis_sigrdze,self.x+padis_sigane,h) 

     elif c.coords(self.pad)[1]<=0: 
      c.coords(self.pad,self.x,0,self.x+padis_sigane,padis_sigrdze) 


x=0;y=0 #Momavalshi 
pad1=chogani(0,1) 
pad2=chogani(w-padis_sigane,1) 
def K(event): 
    pad1.shxuili() 
    pad2.shxuili() 
    if event.keysym=='w': 
     c.move(pad1.pad,0,-padis_sichqare) 
    elif event.keysym=='s': 
     c.move(pad1.pad,0,padis_sichqare) 
    elif event.keysym=='Up': 
     c.move(pad2.pad,0,-padis_sichqare) 
    elif event.keysym=='Down': 
     c.move(pad2.pad,0,padis_sichqare) 
def R(event): 
    print("shen aushvi ", event.char) 
root.bind("<KeyPress>",K) 
root.bind("<KeyRelease>",R) 
root.focus_set() 
c.pack() 
root.mainloop() 

回答

2

在其他模塊 - 像PyGame - 您使用的變量,比如和up_pressed = True/False被按下或釋放鍵,當你改變。接下來創建mainloop來做這個變量來移動物體。由於tkinter早已mainloop所以你可以用after()執行定期自身的功能,這將檢查w_pressed/up_pressed和移動對象。

簡單(工作)例如:

它檢查wup和顯示True/False爲兩個鍵。

import tkinter as tk 

# --- functions --- 

def pressed(event): 
    global w_pressed 
    global up_pressed 

    if event.keysym == 'w': 
     w_pressed = True 
    elif event.keysym == 'Up': 
     up_pressed = True 

def released(event): 
    global w_pressed 
    global up_pressed 

    if event.keysym == 'w': 
     w_pressed = False 
    elif event.keysym == 'Up': 
     up_pressed = False 

def game_loop(): 

    # use keys 
    print(w_pressed, up_pressed) 

    # run again after 500ms 
    root.after(500, game_loop) 

# --- data --- 

w_pressed = False 
up_pressed = False 

# --- main --- 

root = tk.Tk() 

root.bind("<KeyPress>", pressed) 
root.bind("<KeyRelease>", released) 

# start own loop 
game_loop() 

root.mainloop()