0

我必须在 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() 中。所以,我可以生成鱼,但它们不会移动。

与这里的很多东西相比,这是小联盟,但我们将不胜感激。谢谢

4

1 回答 1

0

您的UnboundLocalError: local variable 'whichfish' referenced before assignment问题正在发生,因为dxanddy被允许具有 value 0,但您只为whichfishifdxdy非零分配一个值。

解决此问题的一种方法:将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. 您还会遇到其他一些问题,但这是最直接的问题。

于 2013-10-04T22:53:27.210 回答