2017-05-19 24 views
2

如何使用2鍵在畫布上移動某物?在有人告訴我說我沒有做一些研究之前,我做了。我仍然問這是因爲我不知道他們在說什麼。人們正在談論我不知道的迷你國家和命令。同時按下2個鍵可以對角線移動tkinter?

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中的事件處理程序將始終響應一個按鍵。如果約束是你不能使用「迷你狀態」,那麼你不能這樣做。 –

回答

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

那麼,你可以開始運行代碼,看看它是否做你想要的。然後嘗試一次更改一行,直到您對結果滿意爲止:) – Josselin