python调用类似的变量

时间:2017-10-16 16:54:55

标签: python tkinter self

我使用tkinter与self有一个大问题,这是我的代码 请人们回答,谢谢!我得到的错误类似于self could not be given a variable outside a function

from tkinter import *
root = Tk()

class start():
    global self
    self = root

    def __init__():
        self.title('__init__')
        self.geometry('300x300')

    __init__(self) 

class window_extra():

    def canvas(self):
        global self
        selfc = Canvas(self, bg='black').pack()

    canvas(self)

self.mainloop()

谢谢!

2 个答案:

答案 0 :(得分:3)

您不应将self用作变量名,因为它用于指定某些内容是否是该类实例的属性。

您不需要在类中使用全局,因为在处理类中所需的变量时,大多数情况下都会使用类属性。

根据您显示的代码判断我认为您正在尝试做这样的事情:

from tkinter import *

class start():

    def __init__(self, root):
        self.master = root
        self.master.title('__init__')
        self.master.geometry('300x300')
        Canvas(self.master, bg='black').pack()

root = Tk()
start(root)
root.mainloop()

但是我相信你正在努力使用OOP编程方法,如果是这种情况,我建议不要使用OOP开始。

也许在youtube上学习一些教程或者打开Codecadamy。

回应你的意见:

  

在我的意见中使用init是一个坏主意。我用它作为常规def。如果我使用self global,我无所谓,除非函数/类变量被称为self。

     

我尊重正确使用 init ,但我只是找到了所有内容, init 和self.master我只是没有得到它!

缺乏对事物的理解并不意味着所说的事情是坏的。 self.master的使用是为了提供一个与Th()根变量相关联的类属性。这允许类中的任何方法与Tk()的实例交互。我无法与其他编程语言对话,但self的使用在Python的OOP中非常重要。保留self以引用对象的实例或类属性可能不是100%,但它是self的已接受和已知用法,并且实际上不应该被更改/覆盖。

答案 1 :(得分:0)

为了简单起见,我进行了重组,但我认为在进入GUI路线之前需要更好地理解Python中的对象。我认为你的意思是这样的:

from tkinter import *

# creates a subclass of Tk() called 'Application'; class names by convention
# use CamelCase; best to stick with convention on this one

class Application(tkinter.Tk):

    # you don't have to create an explicit invocation of '__init__', it 
    # is automatically run when you instantiate your class (last line)

    def __init__():
        super().__init__()  # initialize the super class (the 'tkinter.Tk()')

        self.title('__init__')  # use 'self' to refer to this object - do not declare it as global!  it is only valid within the object!
        self.geometry('300x300')

        self.my_canvas = tkinter.Canvas(self, bg='black') # save an instance of your canvas for easy reference later
        self.my_canvas.pack()  # pack as a separate step (only required if you plan to use the canvas later... or ever)

        self.mainloop()  # begin the tkinter loop

# this 'if __name__ ...' is a good idea in most cases, allows you to import `Application` into other
# files without actually running it unless you want to from that other file

if __name__ == '__main__':
    Application()  # start your class
相关问题