我在Python 3.4.4中有一个使用Tkinter的程序,它应该在屏幕周围移动一个方块。
不幸的是,canvas.bind
似乎在while循环中不起作用,但它需要在while循环内部,否则方块不会移动。这是因为我每次在循环运行时都在技术上绘制一个具有不同x,y,x1和y1坐标的新正方形,并且绑定是使正方形根据箭头键在每个方向上移动的原因。
所以这里是代码:
from tkinter import *
import time, random
tk = Tk()
canvas = Canvas(tk, width = 1000, height = 1000)
canvas.pack()
def move(event):
if event.keysym == 'Up':
y-=10
y1-=10
elif event.keysym == 'Down':
y+=10
y1+=10
elif event.keysym == 'Right':
x+=10
x1+=10
elif event.keysym == 'Left':
x+=10
x1+=10
background = canvas.create_rectangle(0, 0, 1000, 1000, fill = 'orange') #draws background
ranNum=random.random()*960 #Creates a random number
ranNum1=random.random()*960 #Creates a random number
food = canvas.create_rectangle(ranNum, ranNum1, ranNum + 15, ranNum1 + 15, fill='green') #creates food
r1 = None
o = 0
length = 4
x = 500
y = 500
x1 = 515
y1 = 515
while o < length:
if canvas.find_overlapping(ranNum, ranNum, ranNum + 15, ranNum1 + 15) == True:
x+=5
y+=5
x1+=5
y1+=5
canvas.delete(food)
r=canvas.create_rectangle(x, y, x1, y1, fill = 'blue')
canvas.bind('<KeyPress-Up>', move )
canvas.bind('<KeyPress-Down>', move)
canvas.bind('<KeyPress-Left>', move)
canvas.bind('<KeyPress-Right>', move)
time.sleep(.0)
canvas.delete(r1)
tk.update()
r1 = r
答案 0 :(得分:0)
不要更改x或y,需要为每个更改事项配置canvas项目配置