我必须在 Python 中制作一个“鱼缸”,它在 Tkinter 中使用画布。在其中,我需要可以通过按下按钮生成的鱼,它们会沿 dx、dy 方向移动,其中 dx 和 dy 都是为每条生成的鱼生成的介于 -3 和 3 之间的随机值。一旦他们接近坦克的边缘,他们应该在相反的方向反弹(如 DVD 屏幕保护程序)。
这是我到目前为止的代码:
import time
import random
from Tkinter import *
tank = Tk()
tank.title("Fish Tank")
tankwidth = 700 # (the background image is 700 by 525)
tankheight = 525
x = tankwidth/2
y = tankheight/2
fishwidth = 78 # (the fish image is 78 by 92)
fishheight = 92
fishx = fishwidth/2
fishy = fishheight/2
dx = 0
dy = 0
canvas = Canvas(tank,width=tankwidth,height=tankheight)
canvas.grid(row=0, column=0, columnspan=3)
bg = PhotoImage(file = "tank.gif")
left = PhotoImage(file = "fishleft.gif")
right = PhotoImage(file = "fishright.gif")
background = canvas.create_image(x,y,image=bg)
rightfish = canvas.create_image(-1234,-1234, image=right)
leftfish = canvas.create_image(-1234,-1234, image=left)
def newfish():
x = random.randrange(fishx+5, tankwidth-(fishx+5)) # +5 here so even the biggest dx or dy
y = random.randrange(fishy+5, tankheight-(fishy+5)) # won't get stuck between the border
dx = random.randrange(-3,4)
dy = random.randrange(-3,4)
leftfish = canvas.create_image(x,y, image=left)
rightfish = canvas.create_image(-1234,-1234, image=right)
updatefish(leftfish,rightfish,x,y,dx,dy)
def updatefish(left,right,x,y,dx,dy):
x += dx
y += dy
if dx < 0:
whichfish = left
canvas.coords(right,-1234,-1234)
if dx > 0:
whichfish = right
canvas.coords(left,-1234,-1234)
if x < fishx or x > tankwidth-fishx:
dx = -dx
if y < fishy or y > tankheight-fishy:
dy = -dy
print x, y, dx, dy
canvas.coords(whichfish, x,y)
canvas.after(100, updatefish, leftfish,rightfish,x,y,dx,dy)
newfish()
new = Button(tank, text="Add Another Fish", command=newfish)
new.grid(row=1,column=1,sticky="NS")
tank.mainloop()
我认为问题出在这里:
rightfish = canvas.create_image(-1234,-1234, image=right)
leftfish = canvas.create_image(-1234,-1234, image=left)
有了它,当我生成一条鱼时,一个鱼实例将停留在它生成的位置,第二个鱼将按预期移动。没有它,我会收到“UnboundLocalError: local variable 'whichfish' referenced before assignment”或抱怨 leftfish 或 rightfish 不存在的错误,即使它们在 updatefish() 中使用之前已经生成并出现在 newfish() 中。所以,我可以生成鱼,但它们不会移动。
与这里的很多东西相比,这是小联盟,但我们将不胜感激。谢谢