2016-10-12 40 views
0

我有一個簡單的程序,它是爲了在畫布中水平左右移動一個球。用戶將使用左鍵和右鍵相應地每次移動5個像素。如果球的x座標小於40或大於240,那麼它將不會執行任何操作。爲什麼我的對象在錯誤的方向移動

try:  
    import tkinter as tk 
except ImportError: 
    import Tkinter as Tk 

window = tk.Tk() 
game_area = tk.Canvas(width=270, height=400, bd=0, highlightthickness=0, 
         bg="white") 

ball = game_area.create_oval(10, 10, 24, 24, fill="red") 
game_area.move(ball, 120, 4) 
coords = 120 

def move_left(event): 
    global coords 
    if coords < 40: 
     pass 
    else: 
     coords = int(coords)- 5 
     game_area.move(ball, coords, 4) 
    game_area.update() 

def move_right(event): 
    global coords 
    if coords > 240: 
     pass 
    else: 
     coords = int(coords)+5 
     game_area.move(ball, coords, 4) 
    game_area.update() 

window.bind("<Left>", move_left) 
window.bind("<Right>", move_right) 
game_area.pack() 
window.mainloop() 

不過,按下任一鍵移動球向右(超過5個像素跨越)和關閉屏幕儘管if功能這是爲了防止這一點。

回答

2

根據Tkinter Canvas documentationmove方法的第二個參數dx是一個偏移量。嘗試將它稱爲

game_area.move(ball, -5, 4) 

然後,您不需要以下行。

coords = int(coords)- 5 
+0

謝謝,雖然他們朝着正確的方向移動,球仍然向下移動,我希望它保持在y軸的位置。 – Ernxst

+0

@Ernxst第三個參數「dy」也是一個偏移量。將其從4更改爲0. –

+0

沒關係!重新閱讀您發佈的內容後,我將其設置爲4。 – Ernxst

相關問題