使用python从类返回变量

使用python从类返回变量,python,tkinter,Python,Tkinter,嘿,我试图从一个类中获取一个变量,但由于某些原因,它无法通过。这可能真的很简单,但我真的想不出什么 这是代码,它还没有完成,我只做了一个登录屏幕: from tkinter import * import tkinter.messagebox as tm correct = False #-------------Functions----------------------------------------------------- class LoginMenu(Frame):

嘿,我试图从一个类中获取一个变量,但由于某些原因,它无法通过。这可能真的很简单,但我真的想不出什么

这是代码,它还没有完成,我只做了一个登录屏幕:

from tkinter import *
import tkinter.messagebox as tm
correct = False
#-------------Functions-----------------------------------------------------

class LoginMenu(Frame):
    def __init__(self, master):
        super().__init__(master)

        self.label_2 = Label(self, text="Welcome to the rota system")
        self.label_3 = Label(self, text="Please enter the password to continue:")
        self.label_1 = Label(self, text="Password")

        self.entry_1 = Entry(self)

        self.label_1.grid(row=3, sticky=W)
        self.label_2.grid(row=1, sticky=W)
        self.label_3.grid(row=2, sticky=W)
        self.entry_1.grid(row=3, sticky=W)


        self.logbtn = Button(self, text="Login", command = self.login_btn_clicked)
        self.logbtn.grid(columnspan=2)

        self.pack()

    def login_btn_clicked(self):

        password = self.entry_1.get()

        if password == "1234":
            correct = True

        else:
            tm.showerror("Login error", "Incorrect password")
        return correct



#-----------------Main-Program----------------------------------------------

window = Tk()
LoginMenu(window)
if correct == True:
    print("Yay")
    LoginMenu.self.destroy()
window.mainloop()

类中的变量只有一个局部作用域

一个好方法是将变量
correct
定义为类成员:

class LoginMenu(Frame):
    def __init__(self, master):
        super().__init__(master)
        self.correct = False
然后在函数中设置它:

def login_btn_clicked(self):

        password = self.entry_1.get()

        if password == "1234":
            self.correct = True
您可以通过从全局范围访问它(不需要
==True
,顺便说一句)


问题是,这在你的情况下是行不通的。在
if
构造之后进入主循环。请查看Tkinter文档,了解如何正确构造Tkinter应用程序。

类中的变量仅具有局部范围

一个好方法是将变量
correct
定义为类成员:

class LoginMenu(Frame):
    def __init__(self, master):
        super().__init__(master)
        self.correct = False
然后在函数中设置它:

def login_btn_clicked(self):

        password = self.entry_1.get()

        if password == "1234":
            self.correct = True
您可以通过从全局范围访问它(不需要
==True
,顺便说一句)


问题是,这在你的情况下是行不通的。在
if
构造之后进入主循环。请查看Tkinter文档,了解如何正确构造Tkinter应用程序。

要在局部范围内引用全局变量,必须在类中定义该变量,如下所示:

global correct

(在函数login内单击)

要在局部范围内引用全局变量,必须在类内定义该变量,如下所示:

global correct

(在函数login_btn_单击的内部)

correct
当密码不正确时,不会声明变量,因此它不能
返回
。即使声明了它,它也只存在于类方法的范围内。它不是全局变量,不应在类中使用。
correct
当密码不正确时,不会声明变量,因此它不能
return
。即使声明了它,它也只存在于类方法的范围内。它不是全局变量,您不应该在类中使用它。虽然这在技术上是正确的,但全局变量不是非常pythonic:)虽然这在技术上是正确的,但全局变量不是非常pythonic:)