我应该如何在python TKinter中实现keybinded space函数?

时间:2017-11-14 03:15:05

标签: python user-interface tkinter python-imaging-library

我正在尝试使用python的Tkinter模块创建一个GUI,它将在平台上绘制太空飞船的图片。我希望能够键入空格键,以便将y(vy)的速度提高3米/秒。但出于某种原因,当我尝试实现它时,它不起作用。这是我的代码,任何人都可以帮助我吗?

from Tkinter import Tk, Canvas
from PIL import Image, ImageTk

w,h= 800,600
g = -1.6
dt = 0.05
y = 100.0
vy = 0.0
t = 0.0

def tick():
   global y, vy, t
   y+= vy*dt
   vy += g*dt
   t+= dt
   print t, y, vy
   yp = 0.7*h-0.7*h*y/100.0
   canvas.coords(ship, w/4, yp)
   canvas.itemconfigure(txt,text='%0.2f'%vy)
   if y >= 0.0:
      canvas.after(1,tick)


root = Tk()
canvas = Canvas(root, width = w, height = h, bg = 'black')
canvas.pack()

img1 = Image.open('earthrise.jpg').resize((w,h)) 
pmg1 = ImageTk.PhotoImage(img1)
ship = canvas.create_image(w/2,h/2, image = pmg1)

img2 = Image.open('eagle.jpg').resize((200,200)) 
pmg2 = ImageTk.PhotoImage(img2)
ship = canvas.create_image(w/4,0, image = pmg2)

canvas.create_rectangle(w/4-150, int(0.5+0.7*h)+100,w/4 + 150, 
int(0.5+0.7*h)+125, outline = 'green', fill = 'green')
f=('Times',36,'bold')
txt=canvas.create_text(w-100,50,text='0.0',font=f,fill='white')


def space(evt):

    vy+=3





root.bind('<space>',space)



print t,y,vy

canvas.after(1000, tick)
root.mainloop()

0 个答案:

没有答案