0

Tkinter でキャンバスを使用する Python で「水槽」を作成する必要があります。その中で、ボタンを押すことでスポーンでき、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)

これにより、魚をスポーンすると、魚の 1 つのインスタンスがスポーンされた場所にとどまり、2 つ目のインスタンスが想定どおりに移動します。それがないと、「UnboundLocalError: ローカル変数 'whichfish' が割り当て前に参照されました」というメッセージが表示されるか、または updatefish() で使用される前に生成されて newfish() に表示されているにもかかわらず、leftfish または rightfish が存在しないというエラーが表示されます。魚をスポーンすることはできますが、魚は動きません。

これは、ここにある多くのものに比べてマイナーリーグですが、どんな助けもいただければ幸いです. ありがとう

4

1 に答える 1

0

とが値を持つことが許可されているため、UnboundLocalError: local variable 'whichfish' referenced before assignment問題が発生していますが、とがゼロ以外の場合にのみ値を割り当てます。dxdy0whichfishdxdy

これを修正する 1 つの方法:randrangeステートメントを次のように置き換えます。

dx = random.choice([-3, -2, -1, 1, 2, 3])
dy = random.choice([-3, -2, -1, 1, 2, 3])

動かない魚を取得している理由については、左右の魚の画像を に割り当ててから、魚のキャンバス IDとしてwhichfish使用しています。代わりにこれを試してください:whichfish

whichfish = leftfish

それ以外の

whichfish = left

についても同様ですrightfish。他にもいくつか問題に直面することになりますが、それが最も差し迫った問題です。

于 2013-10-04T22:53:27.210 に答える