2017-05-19 19 views
2

2つのキーでキャンバス上で何かを動かすにはどうしたらいいですか?誰かが私にいくつかの研究をしなかったと言う前に、私はしました。私がまだこれを求めているのは、彼らが何を話しているのか分からないからです。人々は私が知らない小さな州や命令について話している。2つのキーを同時に押すと、斜めに移動できますか?

from tkinter import * 

def move(x,y): 
    canvas.move(box,x,y) 

def moveKeys(event): 
    key=event.keysym 
    if key =='Up': 
     move(0,-10) 
    elif key =='Down': 
    move(0,10) 
    elif key=='Left': 
    move(-10,0) 
    elif key=='Right': 
     move(10,0) 

window =Tk() 
window.title('Test') 

canvas=Canvas(window, height=500, width=500) 
canvas.pack() 

box=canvas.create_rectangle(50,50,60,60, fill='blue') 
canvas.bind_all('<Key>',moveKeys) 

一度に2つのキーを移動する方法はありますか?私はミニフォーマットではなく、このフォーマットを使用して完成させたいと思います。

+0

あなたはあなたが指定した形式を使用してそれを行うことはできません。 tkinterのイベントハンドラは、常に1回のキー入力に応答します。制約が「ミニ状態」を使用できないということであれば、それはできません。 –

答えて

0

あなたが話している「ミニ状態」の方法がこの回答(Python bind - allow multiple keys to be pressed simultaneously)を参照している場合、実際に理解するのは難しくありません。

は、その哲学を次のコードの修正&コメントしたバージョン以下を参照してください。

from tkinter import tk 

window = tk.Tk() 
window.title('Test') 

canvas = tk.Canvas(window, height=500, width=500) 
canvas.pack() 

box = canvas.create_rectangle(50, 50, 60, 60, fill='blue') 

def move(x, y): 
    canvas.move(box, x, y) 

# This dictionary stores the current pressed status of the (← ↑ → ↓) keys 
# (pressed: True, released: False) and will be modified by Pressing or Releasing each key 
pressedStatus = {"Up": False, "Down": False, "Left": False, "Right": False} 

def pressed(event): 
    # When the key "event.keysym" is pressed, set its pressed status to True 
    pressedStatus[event.keysym] = True 

def released(event): 
    # When the key "event.keysym" is released, set its pressed status to False 
    pressedStatus[event.keysym] = False 

def set_bindings(): 
    # Bind the (← ↑ → ↓) keys's Press and Release events 
    for char in ["Up", "Down", "Left", "Right"]: 
     window.bind("<KeyPress-%s>" % char, pressed) 
     window.bind("<KeyRelease-%s>" % char, released) 

def animate(): 
    # For each of the (← ↑ → ↓) keys currently being pressed (if pressedStatus[key] = True) 
    # move in the corresponding direction 
    if pressedStatus["Up"] == True: move(0, -10) 
    if pressedStatus["Down"] == True: move(0, 10) 
    if pressedStatus["Left"] == True: move(-10, 0) 
    if pressedStatus["Right"] == True: move(10, 0) 
    canvas.update() 
    # This method calls itself again and again after a delay (80 ms in this case) 
    window.after(80, animate) 

# Bind the (← ↑ → ↓) keys's Press and Release events 
set_bindings() 

# Start the animation loop 
animate() 

# Launch the window 
window.mainloop() 
+0

13歳の脳がそれを処理できると期待していますか? – 21harrisont

+0

さて、コードを実行して、あなたが望むことができるかどうかを調べることができます。あなたは結果に満足しているまで一度に1行を変更するとそれを実験: – Josselin

関連する問題