需要超过0个值才能解包(使用tkinter时出现变量错误时的python坐标)

2024-09-28 01:33:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用tkinter克隆太空入侵者。。。在

问题是我遇到了一个错误,它说ValueError:当我的“shot”由于达到画布限制而被删除时,需要超过0个值才能解包变量赋值(请继续阅读),以阻止“shot”不断超出画布的可见区域。。。在

我在这里发布的代码只是目前为止我所拥有的整个游戏代码的一小部分,但它与我在实际项目中使用的“Shot”行为完全相同。。。在

我知道代码是有效的,而且“镜头”会消失,换句话说。。。它正在工作,但是我一直在外壳上发现这个错误,当我把这个函数和其他9个函数(那些让入侵者射击的函数)并排使用时,程序开始变得迟钝和有缺陷,几秒钟后它就停止工作了。。。在

所以我有点怀疑,破坏我程序的是那个错误,不知道该怎么做。在

希望你能在这里帮我。谢谢您!在

原谅我糟糕的英语技能。在

from Tkinter import *
import os

def LoadImage(name):
    rute = os.path.join('Imagenes',name)
    image = PhotoImage(file=rute)
    return image

root=Tk()

DxShot= 0 #Globals of Directions on x and y
DyShot= -3

def PlayWindow():
    root.withdraw()
    VentanaPlay= Toplevel()
    VentanaPlay.title("Kill'em all!'")
    VentanaPlay.resizable(width=NO, height=NO)
    VentanaPlay.geometry("540x540")

    def Shot():
        x,y= CanvPlay.coords(Ship) #This reads the place from where the shot will have to be created
        ShotImage=LoadImage("Shot.gif")
        Shot1=CanvPlay.create_image(x, y-22, image=ShotImage)
        CanvPlay.img=ShotImage
        def ShotMove():
            global DxShot, DyShot
            x1,y1= CanvPlay.coords(Shot1) #here's where I'm getting the error...
            if y1+DyShot<=0:
                CanvPlay.delete(Shot1) #Also, if I use destroy instead of delete it says "destroy() takes exactly 1 argument (2 given)"
                print("Shot deleted")
            CanvPlay.coords(Shot1, x1+DxShot, y1+DyShot)
            CanvPlay.after(3,ShotMove)
        ShotMove()
        VentanaPlay.after(0,ShotMove)

    def Fire(event):
        Shot()

    CanvPlay= Canvas(VentanaPlay, width=540, height=540, bg="white")
    CanvPlay.config(cursor="dotbox")
    CanvPlay.place(x=-1,y=-1)
    CanvPlay.bind("<space>", Fire)
    CanvPlay.focus_set()

    ShipImage= LoadImage("Ship.gif")
    Ship= CanvPlay.create_image(260, 520, image=ShipImage)

    VentanaPlay.mainloop()

Buttun= Button(root, text= "click me", command=PlayWindow)
Buttun.pack()
root.mainloop()

以下是我得到的完整回溯错误:

^{pr2}$

Tags: 函数代码imagedef错误rootshotloadimage
2条回答

根本问题是CanvPlay.coords(Shot1)返回的是空列表或无,而您的代码没有准备好处理这种情况。例如,如果删除要获取其坐标的项,则可能会发生这种情况。在

实际上,ShotMove函数有删除快照的代码,然后它继续尝试再次移动快照。如果删除快照,则可能不想再次使用after来移动快照。也许简单的解决方案是将ShotMove函数改为如下所示:

def ShotMove():
    global DxShot, DyShot
    x1,y1= CanvPlay.coords(Shot1) #here's where I'm getting the error...
    if y1+DyShot<=0:
        CanvPlay.delete(Shot1) 
        print("Shot deleted")
    else:
        CanvPlay.coords(Shot1, x1+DxShot, y1+DyShot)
        CanvPlay.after(3,ShotMove)

代码中还有另一个问题,即多次调用mainloop。一般来说,您应该只调用mainloop一次。这可能是您的程序在几秒钟后变得滞后和错误的部分原因。在

您需要以某种方式存储快照列表(shot1),但使用嵌套函数的方式行不通。在

嵌套函数可能会产生令人困惑的结果,因为Python不计算函数中的每个变量,并在定义变量时将其存储起来,因此在使用时会访问它们。因此,当您第一次在Shot()中调用ShotMove()时,解释器会查找它找到的名为Shot1的内容。但是,当您试图将ShotMove函数传递到Shot函数之外并在那里调用它时,解释器找不到任何Shot1(它已不存在)。我假设奇怪的错误(而不是NameError之类的)可能是因为python可能会在函数初始定义时(而不是每次运行时)检查namererrors。在

相关问题 更多 >

    热门问题