我在move_r函数中有after语句。但是,当我按空格键时,它说
TypeError: move_r() missing 1 required positional argument: 'event'
我比较知道这意味着什么,但我无法弄清楚要改变什么我的程序应该画一个火箭,然后当你点击空间时火箭向上移动。不幸的是,我的程序每次点击空间时都会上升100,而不是一旦我的目标是一个命中空间就自己上升。 我的代码是:
from tkinter import *
import random, time
tk = Tk()
tk.wm_attributes('-topmost', 1)
canvas = Canvas(tk, width=1000, height=1000, bd=0)
canvas.pack()
def rocket(): #draws rocket
rocketbase=canvas.create_rectangle(x2+50, y2-50, x3-50, y3-90, fill ='blue')
rrocketfin=canvas.create_rectangle(x2+60, y2-50, x3-40, y3-20, fill ='#e69100')
lrocketfin=canvas.create_rectangle(x2+40, y2-50, x3-60, y3-20, fill ='#e69100')
mrocketfin=canvas.create_rectangle(x2+54, y2-50, x3-53, y3-20, fill ='#e69100')
lrockethead=canvas.create_rectangle(x2+45, y2-125, x3-60, y3-70, fill ='#e69100')
rrockethead=canvas.create_rectangle(x2+60, y2-125, x3-45, y3-70, fill ='#e69100')
def move_r(event):
if event.keysym == 'space':
global y2
global y3
y2-=100
y3-=100
canvas.after(100, move_r )
x2=460
y2=940
x3=570
y3=900
r1=None
tk.bind('<KeyPress-space>', move_r)
while True:
background = canvas.create_rectangle(0, 0, 1000, 1000, fill = 'red')
base=canvas.create_rectangle(0, 1000, 1000, 900, fill='#86592d')
rocket()
tk.update()
tk.mainloop()
答案 0 :(得分:1)
这是一个移动的火箭;它没有解决你所有的问题,但它解决了你问的问题:
该事件是key_press - 当您按空格键并将其发送到事件处理程序时会生成该事件。
事件处理程序接收事件并对其进行操作(识别哪个事件,并将流引导到应该的位置 - 这里,移动火箭)。
移动火箭就是这样,它使用回调循环移动火箭。
from tkinter import *
import random, time
tk = Tk()
tk.wm_attributes('-topmost', 1)
canvas = Canvas(tk, width=1000, height=1000, bd=0)
canvas.pack()
def rocket(): #draws rocket
rocketbase=canvas.create_rectangle(x2+50, y2-50, x3-50, y3-90, fill ='blue')
rrocketfin=canvas.create_rectangle(x2+60, y2-50, x3-40, y3-20, fill ='#e69100')
lrocketfin=canvas.create_rectangle(x2+40, y2-50, x3-60, y3-20, fill ='#e69100')
mrocketfin=canvas.create_rectangle(x2+54, y2-50, x3-53, y3-20, fill ='#e69100')
lrockethead=canvas.create_rectangle(x2+45, y2-125, x3-60, y3-70, fill ='#e69100')
rrockethead=canvas.create_rectangle(x2+60, y2-125, x3-45, y3-70, fill ='#e69100')
def handle_key_press(e):
if e.keysym == 'space':
move_r()
def move_r():
global y2
global y3
y2 -= 50
y3 -= 50
rocket()
tk.update()
canvas.after(100, move_r)
x2=460
y2=940
x3=570
y3=900
r1=None
tk.bind('<KeyPress-space>', handle_key_press)
background = canvas.create_rectangle(0, 0, 1000, 1000, fill = 'red')
base = canvas.create_rectangle(0, 1000, 1000, 900, fill='#86592d')
rocket()
tk.update()
tk.mainloop()