2016-07-04 53 views
0

我想在Tkinter中創建一個可移動的精靈;它的工作原理,但我不確定綁定一個Canvas是最好的解決方案。按「w」後會出現延遲,例如,角色移動一次,停止幾秒鐘,然後開始移動一點點。Tkinter平滑運動?

代碼:

import Tkinter as t 

tk = t.Tk() 
w = t.Button() 
c = t.Canvas(tk, bg = "#000000", bd = 3) 
x = 20 
y = 20 

img = t.PhotoImage(file = "hi.png") 
c.create_image(x, y, image = img) 
coord = 10, 50, 240, 210 

def clearboard(): 
    c.delete("all"); 


def key(event): 
    global y 
    global x 
    pr = event.char 
    if(pr is "w"): 
     y -= 5 
    if(pr is "s"): 
     y += 5 
    if(pr is "a"): 
     x -= 5 
    if(pr is "d"): 
     x += 5 
    c.delete("all"); 
    c.create_image(x, y, image = img) 



w = t.Button(tk, command = clearboard, activebackground = "#000000", activeforeground = "#FFFFFF", bd = 3, fg = "#000000", bg = "#FFFFFF", text = "Clear", relief="groove") 


c.focus_set() 
c.bind("<Key>", key) 

w.pack() 
c.pack() 
tk.mainloop() 

我的問題是,如何刪除剛纔提到的延遲,使運動更流暢一點?

在此先感謝。

回答

2

好的,我找到了我的問題的答案。我剛剛創建了一個遊戲循環,並添加了一個velx變量,並添加了綁定<KeyPress><KeyRelease>

代碼:

import Tkinter as t 

tk = t.Tk() 
w = t.Button() 
c = t.Canvas(tk, bg = "#000000", bd = 3, width = 480, height = 360) 
velx = 0 
x = 240 
img = t.PhotoImage(file = "hi.png") 
c.create_image(x, 200, image = img) 

def move(): 
    global x 
    c.delete("all"); 
    x += velx; 
    c.create_image(x, 200, image = img) 
    tk.after(10, move) 

def clearboard(): 
    c.delete("all"); 


def key_press(event): 
    global velx 
    pr = event.char 
    if(pr is "a"): 
     velx = -5 
    if(pr is "d"): 
     velx = 5 


def key_release(event): 
    global velx 
    velx = 0 


w = t.Button(tk, command = clearboard, activebackground = "#000000", activeforeground = "#FFFFFF", bd = 3, fg = "#000000", bg = "#FFFFFF", text = "Clear", relief="groove") 


c.focus_set() 
c.bind("<KeyPress>", key_press) 
c.bind("<KeyRelease>", key_release) 

move() 
w.pack() 
c.pack() 
tk.mainloop()