【问题标题】:Python unable to assign a value in a classPython无法在类中赋值
【发布时间】:2015-07-22 01:30:27
【问题描述】:

我无法在类中传递/分配值。 这是我的类定义,基本上我想根据 tod(time of day) 更改颜色。

class Meter(tk.Canvas):

    def __init__(self,master,*args,**kwargs):
        super(Meter,self).__init__(master,*args,**kwargs)

        self.tod=tod
        self.layoutparams(tod)
        self.graphics()
        self.createhand()
        self.setrange()


    def layoutparams(self,tod):
        # set parameters that control the layout
        height = int(self['height'])
        width = int(self['width'])


        # find a square that fits in the window
        if(height*2 > width):
            side = width
        else:
            side = height*2

        # set axis for hand
        self.centrex = side/2
        self.centrey = side/2

        # standard with of lines
        self.linewidth = 2

        # outer radius for dial
        self.radius = int(0.40*float(side))

        # set width of bezel
        self.bezel = self.radius/15
        self.bezelcolour1 = 'green'
here is where i change the colour
        if (tod=='day'):
            self.bezelcolour2 = 'black'
        else:
            self.bezelcolour2 = 'white'
        self.bezelcolour3 = 'red'

        # set lengths of ticks and hand
        self.majortick = self.radius/8
        self.minortick = self.majortick/2

这是我做实例的方法

    w=Meter(self,height = 400,width = 400)
    w.tod='day'

我收到了这个错误

line 27, in __init__
    self.tod=tod
NameError: name 'tod' is not defined

怎么了?

【问题讨论】:

    标签: class python-3.x canvas tkinter


    【解决方案1】:

    问题正是错误告诉您的。您将tod 的值分配给self.tod,但没有名为tod 的变量。

    【讨论】:

      【解决方案2】:

      你必须写:

      w=Meter(self,height = 400,width = 400, tod='day')
      

      最好写成:

      if (self.tod=='day'):
      

      您可能还应该添加一个函数changeTod

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-01-24
        • 1970-01-01
        • 2020-10-11
        • 2019-09-10
        • 1970-01-01
        相关资源
        最近更新 更多