2016-11-27 2 views
1

tkinter에서 작은 빛을 발하는 게임을 만들고 벽에 직면합니다. 컴파일러는 키 이벤트 하나를 잡아 두 번째 사용자가 키를 누르면 첫 번째 사용자 움직임이 멈 춥니 다. 너희들이이 문제를 슬 루잉하는 법을 안다? 여기Tkinter에서 두 개의 키 이벤트를 잡는 법

코드입니다 : - PyGame 같은 -

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

다른 모듈에서 사용자가 키를 누르거나 놓을 때 변경되는 및 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() 
관련 문제