2010-01-26 3 views
3

파이썬에서 문제가 있습니다.Python bind - 여러 키를 동시에 누를 수 있습니다.

저는 Tkinter를 사용하고 있으며 내 양식에서 키 누르기를 수신하는 4 개의 바인드 이벤트가 있습니다. 내 문제는 비동기 적으로 실행되지 않는다는 것입니다. 예를 들어 버튼 하나만 누르면 이벤트가 인식됩니다. 그러나 동시에 두 개의 키를 누르고 있으면 하나의 이벤트가 시작됩니다.

다른 방법이 있습니까?

self.f.bind("w", self.player1Up) 
    self.f.bind("s", self.player1Down) 
    self.f.bind("o", self.player2Up) 
    self.f.bind("l", self.player2Down) 
+1

Tkinter는 게임 환경이 좋지 않을 수 있습니다. 파이 게임을 보셨나요? –

+0

PyGame은 아직 Python 3.x에서는 작동하지 않습니다. 따라서 일반적인 Python 솔루션은 아니며 현재는 Python 3.x +로 이식하지 않는 한 장래에 많은 옵션이 없을 것입니다. 2.x에서 잘 작동합니다. – Shule

답변

9

안타깝게도 시스템의 기본 자동 반복 메커니즘이 다소 유용합니다. 예를 들어, "w"를 길게 누르는 순간 사용중인 Mac에서 언론 및 출시 이벤트가 발생합니다. 눌렀을 때, "o"를 누르면 "o"에 대한 프레스 및 릴리스 스트림을 얻지 만 "w"에 대한 이벤트는 더 이상 발생하지 않습니다.

미니 상태 시스템을 설정하고 키 누르기 및 키 릴리스 이벤트에 바인딩해야합니다. 이것은 어떤 키가 눌려 졌는지 아닌지를 추적 할 수있게합니다. 그런 다음 프레임을 그릴 때마다 기계를 조회하여 어떤 키가 눌려 있는지 확인하고 그에 따라 조치 할 수 있습니다.

다음은 내가 함께 던진 간단한 해킹입니다. 난 단지 내 맥에서, 그리고 파이썬 2.5에서만 테스트했습니다. 나는 "pythonic"또는 능률적 인 시도에 진짜 시도를 만들지 않았다. 이 코드는 그 기술을 설명하기위한 것일뿐입니다. 이 코드를 사용하면 "w"또는 "s"와 "o"또는 "l"을 동시에 눌러 두 개의 패들을 위아래로 움직일 수 있습니다.

'''Example that demonstrates keeping track of multiple key events''' 
from Tkinter import * 

class Playfield: 
    def __init__(self): 
     # this dict keeps track of keys that have been pressed but not 
     # released 
     self.pressed = {} 

     self._create_ui() 

    def start(self): 
     self._animate() 
     self.root.mainloop() 

    def _create_ui(self): 
     self.root = Tk() 
     self.p1label = Label(text="press w, s to move player 1 up, down", 
          anchor="w") 
     self.p2label = Label(text="press o, l to move player 2 up, down", 
          anchor="w") 
     self.canvas = Canvas(width=440, height=440) 
     self.canvas.config(scrollregion=(-20, -20, 420, 420)) 

     self.p1label.pack(side="top", fill="x") 
     self.p2label.pack(side="top", fill="x") 
     self.canvas.pack(side="top", fill="both", expand="true") 

     self.p1 = Paddle(self.canvas, tag="p1", color="red", x=0, y=0) 
     self.p2 = Paddle(self.canvas, tag="p2", color="blue", x=400, y=0) 

     self._set_bindings() 

    def _animate(self): 
     if self.pressed["w"]: self.p1.move_up() 
     if self.pressed["s"]: self.p1.move_down() 
     if self.pressed["o"]: self.p2.move_up() 
     if self.pressed["l"]: self.p2.move_down() 
     self.p1.redraw() 
     self.p2.redraw() 
     self.root.after(10, self._animate) 

    def _set_bindings(self): 
     for char in ["w","s","o", "l"]: 
      self.root.bind("<KeyPress-%s>" % char, self._pressed) 
      self.root.bind("<KeyRelease-%s>" % char, self._released) 
      self.pressed[char] = False 

    def _pressed(self, event): 
     self.pressed[event.char] = True 

    def _released(self, event): 
     self.pressed[event.char] = False 

class Paddle(): 
    def __init__(self, canvas, tag, color="red", x=0, y=0): 
     self.canvas = canvas 
     self.tag = tag 
     self.x = x 
     self.y = y 
     self.color = color 
     self.redraw() 

    def move_up(self): 
     self.y = max(self.y -2, 0) 

    def move_down(self): 
     self.y = min(self.y + 2, 400) 

    def redraw(self): 
     x0 = self.x - 10 
     x1 = self.x + 10 
     y0 = self.y - 20 
     y1 = self.y + 20 
     self.canvas.delete(self.tag) 
     self.canvas.create_rectangle(x0,y0,x1,y1,tags=self.tag, fill=self.color) 

if __name__ == "__main__": 
    p = Playfield() 
    p.start() 
-1

당신은 "< 키 >"에 바인딩 한 다음 그 값을 기준으로 할 작업을 event.char을 확인하고 수행 할 수 있을까? 다중 키가 동시에 눌러 졌을 때 이것이 정상적으로 작동하는지는 모르겠지만 똑같은 문제로 계속 실행될 수 있습니다. 나는 Tk를 오래 사용하지 않았다.

" 키 > 키가 눌 렸습니다.이 키는 콜백에 전달 된 이벤트 개체의 char 멤버로 제공됩니다 (특수 키는 비어있는 문자열 임)."

+0

http://groups.google.com/group/comp.lang.python/browse_thread/thread/88788c3b0b0d51d1/c4b7efe2d71bda93 .. 이렇게하면 원하는 해결책을 찾을 수 있지만 전반적으로 PyGame으로 전환 할 수 있습니다. 여기서 더 나은 옵션이 될 수 있습니다. – Wayne

관련 문제