python调用类似的变量

2024-06-13 21:02:43 发布

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

我在使用带有self的tkinter时遇到了一个很大的问题 请大家回答一下,谢谢!我得到的错误类似于,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()

谢谢!你知道吗


Tags: selfinittkinterdef错误notrootbe
2条回答

为了简单起见,我对其进行了重构,但我认为您需要更好地理解Python中的对象,然后才能深入了解GUI。我想你的意思是这样的:

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

不应将self用作变量名,因为它用于指定某个对象是否是类实例的属性。你知道吗

您不需要在类中使用global,因为在处理通过类所需的变量时,大多数情况下都使用类属性。你知道吗

从你展示的代码来看,我认为你正在尝试这样做:

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()

然而,我相信你正在努力与面向对象编程方法,我建议不要使用面向对象编程开始,如果是这样的情况。你知道吗

也许可以在youtube上看一些教程或者点击Codecadamy。你知道吗

针对您的意见:

In my Opinion using init properly is a bad idea. I use it as a regular def. I doesn't matter if I use self global, unless the function/class variable is called self.

I respect the proper use of init, but I just find the whole thing with, init and self.master I just don't get any of it!

不懂一件事并不意味着说的是坏事。使用self.master可以提供一个类属性,该属性与根Tk()变量相关联。这允许类中的任何方法与Tk()的实例交互。我不能说其他编程语言,但是self的使用在python的OOP中是非常重要的。保留self以引用对象实例或类属性可能不是100%必需的,但它是self的公认和已知用法,确实不应更改/覆盖。你知道吗

相关问题 更多 >