我必须在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:局部变量'哪个'在分配之前引用'或者错误抱怨左鱼或右鱼不存在,即使它们已经产生并出现在newfish()中,然后才会在updatefish()中使用。所以,我可以产鱼,但它们不会移动。
与其他很多东西相比,这是一个小联盟,但任何帮助都会受到赞赏。感谢
答案 0 :(得分:0)
您的UnboundLocalError: local variable 'whichfish' referenced before assignment
问题正在发生,因为dx
和dy
的值为0
,但您只需whichfish
dx
{1}}和dy
非零。
解决此问题的一种方法:将randrange
语句替换为:
dx = random.choice([-3, -2, -1, 1, 2, 3])
dy = random.choice([-3, -2, -1, 1, 2, 3])
至于你为什么要吃不动的鱼:
您要将左右鱼的图像分配到whichfish
,然后您使用whichfish
作为鱼的画布ID 。试试这个:
whichfish = leftfish
而不是
whichfish = left
,同样适用于rightfish
。你还会遇到其他一些问题,但那是最直接的问题。