簡體   English   中英

在其定義類之外使用StringVar

[英]Using StringVar outside of its defining class

我有一個GUI生成一個主窗口以及其中的許多其他頂級窗口。 我正在嘗試使用tkinter的StringVar存儲登錄到程序的當前用戶的用戶名,然后在其他頂級窗口(以及那些窗口中的函數)中調用該變量。 每個“框架”,“頂級”窗口和“主”窗口都有各自獨立的類。 我覺得這是造成問題的原因。 我不太確定如何在我在其中定義的類之外引用StringVar。

這是我嘗試實現的方法:

(tkinter導入為tk)

class main_window(tk.Tk):
    def __init__(self,*args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        self.title('Pilot Flight and Duty Tracker')
        self.geometry('1000x700+250+50')
        self.resizable(width = False, height = False)
        self.frame = None
        self.switch_frame(Cover_Frame)
        Login_Window = Login(self)
        menu = tk.Menu(self)
        self.config(menu=menu)
        filemenu = tk.Menu(menu)
        menu.add_cascade(label="File", menu=filemenu)
        filemenu.add_separator()
        filemenu.add_command(label="Exit", command=self.destroy)
        self.Current_User = tk.StringVar()

這是來自頂層窗口的不同類的方法,該方法嘗試調用變量:

def login(self):
    global Users
    username = self.user_entry.get()
    pw = self.password_entry.get()
    if (username, pw) in Users:
        if (username, pw) == ('Admin', 'AdminPassword'):
            self.after(500, self.destroy)
            self.warn.config(text='Login Successful!', bg='lime green', justify='center')
            main_window.switch_frame(self.master, Blank_Frame)
            Login_Creation = Create_Login(self.master)
        else:
            self.after(500, self.destroy)
            main_window.Current_User.set(username)
            print(main_window.Current_User.get())
            main_window.switch_frame(self.master, Create_Profile)
            self.warn.config(text='Login Successful!', bg='lime green', justify='center')

    else:
        self.warn.config(text="Invalid Username or Password", fg="black", bg='red', justify ='center')

不幸的是,我得到這個錯誤:

AttributeError: type object 'main_window' has no attribute 'Current_User'

我如何在這樣的不同類中正確調用StringVar並在整個程序中使用它?

在使用一個類之前,需要創建一個對象實例,該對象實例將隱式調用__init__方法來設置局部變量。 因此, login第一行應為:

mw = main_window()

那么所有呼叫都應該是mw例如mw.Current_User

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM