处理Python代码中的“Point is not defined”错误

118 阅读2分钟

在编写一个名为Zombie Dice的游戏代码时,尝试使用Point类创建了一个DieViewYellow类,却遇到了“Point is not defined”错误。即使已经导入了graphics库,但错误依然存在。

huake_00015_.jpg 2、解决方案: 导致该错误的原因是Python并不知道Point类位于graphics模块中,因此需要明确告诉Python这一点。有两种方法可以解决此问题:

方法一:在使用Point类时,在类名之前加上graphics.前缀,使其成为graphics.Point。例如:

p2 = graphics.Point(x+25, y+25)

方法二:从graphics模块中直接导入Point类,然后在使用时就不需要加graphics.前缀了。例如:

from graphics import Point

p2 = Point(x+25, y+25)

代码例子:

完整的DieViewYellow类代码如下:

#Die View Yellow
from graphics import *

class DieViewYellow:

def __init__(self, win, center, value):
    """Create a view of a die, e.g.:
       d1 = GDie(myWin, Point(40,50), 20)
    creates a die centered at (40,50) having sides
    of length 20."""

    # first define some standard values
    self.win = win
    #self.background = Color # color of die face
    #self.foreground = Color2 # color of the pips

    # create a square for the face
    if value==0:
        x, y = center.getX(), center.getY()
        p1 = Point(x-25, y-25)
        p2 = Point(x+25, y+25)
        rect = Rectangle(p1,p2)
        rect.draw(win)
        rect.setFill('yellow')


    if value == 1:
        x, y = center.getX(), center.getY()
        p1 = Point(x-25, y-25)
        p2 = Point(x+25, y+25)
        rect = Rectangle(p1,p2)
        rect.draw(win)
        rect.setFill('yellow')
        self.Brain=Text(Point(95,75),'B')
        self.Brain.draw(self.win)

    elif value == 2:
        x, y = center.getX(), center.getY()
        p1 = Point(x-25, y-25)
        p2 = Point(x+25, y+25)
        rect = Rectangle(p1,p2)
        rect.draw(win)
        rect.setFill('yellow')
        self.Brain=Text(Point(95,75),'B')
        self.Brain.draw(self.win)


    elif value == 3:
        x, y = center.getX(), center.getY()
        p1 = Point(x-25, y-25)
        p2 = Point(x+25, y+25)
        rect = Rectangle(p1,p2)
        rect.draw(win)
        rect.setFill('yellow')
        self.Shotgun=Text(Point(95,75),'S')
        self.Shotgun.draw(self.win)


    elif value == 4:
        x, y = center.getX(), center.getY()
        p1 = Point(x-25, y-25)
        p2 = Point(x+25, y+25)
        rect = Rectangle(p1,p2)
        rect.draw(win)
        rect.setFill('yellow')
        self.Foot=Text(Point(95,75),'F')
        self.Foot.draw(self.win)


    elif value == 5:
        x, y = center.getX(), center.getY()
        p1 = Point(x-25, y-25)
        p2 = Point(x+25, y+25)
        rect = Rectangle(p1,p2)
        rect.draw(win)
        rect.setFill('yellow')
        self.Foot=Text(Point(95,75),'F')
        self.Foot.draw(self.win)

    else:
        x, y = center.getX(), center.getY()
        p1 = Point(x-25, y-25)
        p2 = Point(x+25, y+25)
        rect = Rectangle(p1,p2)
        rect.draw(win)
        rect.setFill('yellow')
        self.Shotgun=Text(Point(95,75),'S')
        self.Shotgun.draw(self.win)        

通过以上方法,就可以解决“Point is not defined”错误,并正常使用graphics库中的Point类。