我必须用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:本地变量'whichfish‘在赋值前引用“,或者出现错误,抱怨leftfish或rightfish不存在,即使它们在updatefish()中使用之前已经生成并出现在newfish()中。所以,我可以产卵,但它们不会移动。
与这里的许多东西相比,这只是一个小联盟,但任何帮助都将不胜感激。谢谢
发布于 2013-10-05 06:53:27
之所以会出现UnboundLocalError: local variable 'whichfish' referenced before assignment问题,是因为允许dx和dy的值为0,但是只有在dx和dy不为零的情况下才会将值赋给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也是如此。您还会遇到其他一些问题,但这是最直接的问题。
https://stackoverflow.com/questions/19171217
复制相似问题