2016-07-04 3 views
0

저는 Tkinter에서 움직이는 스프라이트를 만들려고합니다. 그것은 작동하지만 캔버스를 바인딩하는 것이 최선의 해결책인지 잘 모르겠습니다. "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()