如何在tkinter中从不同的类中访问变量?

12
我一直在搜索,但仍然不知道如何在Python中从不同的类中访问变量。 在这种情况下,我想从PageOne类访问变量self.v到PageTwo类。
这是我的代码。
import tkinter as tk
import smtplib

TITLE_FONT = ("Helvetica", 18, "bold")

class SampleApp(tk.Tk):

    def __init__(self):
        tk.Tk.__init__(self)

        container = tk.Frame(self)
        container.pack(side="top", fill="both", expand=True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)

        self.frames = {}
        for F in (StartPage, PageOne, PageTwo):
            frame = F(container, self)
            self.frames[F] = frame

            frame.grid(row=0, column=0, sticky="nsew")

        self.show_frame(StartPage)

    def show_frame(self, c):
        frame = self.frames[c]
        frame.tkraise()

class StartPage(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        label = tk.Label(self, text="PyMail",foreground = "Red", font=("Courier", 30, "bold"))
        label.pack(side="top")
        sublabel = tk.Label(self, text="Bringing you the\n the easiest way of communication",
                            font=("Courier", 15))
        sublabel.pack()

        wallpaper = tk.PhotoImage(file='Python-logo-notext.gif')
        img = tk.Label(self, image=wallpaper)
        img.image = wallpaper
        img.pack(side="top", expand = True)

        button1 = tk.Button(self, text="Click Here to Login to your account",fg="red",
                            command=lambda: controller.show_frame(PageOne))
        button2 = tk.Button(self, text="Go to Page Two",
                            command=lambda: controller.show_frame(PageTwo))
        button2.pack(side="bottom")
        button1.pack(side="bottom")

class PageOne(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller=controller
        label = tk.Label(self, text="Personal Information", font=TITLE_FONT, foreground="blue")
        label.pack(side="top", fill="x", pady=10)
        global optionv
        self.optionv = tk.StringVar()
        self.optionv.set("---Select One---")
        optionm = tk.OptionMenu(self, self.optionv, "---Select One---", "@gmail.com", "@yahoo.com", "@hotmail.com")

        t1 = tk.Label(self, text="Email Account: ")
        self.v = tk.StringVar()
        self.v.set("")
        entry1 = tk.Entry(self, textvariable=self.v)
        t2 = tk.Label(self,text="\nPassword: ")
        self.pwd = tk.StringVar()
        self.pwd.set("")
        entry2 = tk.Entry(self, textvariable=self.pwd)
        entry2.config(show="*")
        lgbutton=tk.Button(self, text="Log In", command=self.login) 
        button = tk.Button(self, text="Go to the start page",
                           command=lambda: controller.show_frame(StartPage))
        #final = tk.Label(self, textvariable=self.v)
        #finalpwd = tk.Label(self, textvariable=self.pwd)

        t1.pack()
        entry1.pack()
        optionm.pack()
        t2.pack()
        entry2.pack()
        #final.pack()
        #finalpwd.pack()
        lgbutton.pack()
        button.pack(side="bottom")

    def login(self):
        value = tk.Label(self, text="Invalid username / password", font=("Courier", 15, "bold"), foreground="red")
        success = tk.Label(self, text="Login was Successful \n (Click ""Continue"" to compose email)", font=("Courier", 15, "bold"), foreground="blue")
        cbutton = tk.Button(self, text="Continue", command=lambda: self.controller.show_frame(PageTwo))
        status = tk.Label(self, text="Please select your email domain", foreground="red")
        if self.optionv.get() == "@gmail.com":
            try:
                global server
                server = smtplib.SMTP("smtp.gmail.com", 587)
                server.ehlo()
                server.starttls()
                server.login(self.v.get()+self.optionv.get(), self.pwd.get())
                success.pack()
                cbutton.pack(side="bottom")
            except:
                value.pack() 
        elif self.optionv.get() == "@yahoo.com":
            try:
                server = smtplib.SMTP("smtp.yahoo.com", 587)
                server.ehlo()
                server.starttls()
                server.login(self.v.get()+self.optionv.get(), self.pwd.get())
                success.pack()
                cbutton.pack(side="bottom")
            except:
                value.pack()

        elif self.optionv.get() == "@hotmail.com":
            try:
                server = smtplib.SMTP("smtp.live.com", 587)
                server.ehlo()
                server.starttls()
                server.login(self.v.get()+self.optionv.get(), self.pwd.get())
                success.pack()
                cbutton.pack(side="bottom")
            except:
                value.pack()
        else:
            status.pack()

class PageTwo(tk.Frame): 

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        label = tk.Label(self, text="Compose Mail", font=TITLE_FONT, foreground="green") 
        label.pack(side="top", fill="x", pady=10)

        self.reciever = tk.StringVar()
        self.reciever.set("")
        senderl = tk.Label(self, text="Send to: ")
        rmail = tk.Entry(self, textvariable=self.reciever)

        self.senderoption = tk.StringVar()
        self.senderoption.set("---Select One---")
        senderdomain = tk.OptionMenu(self, self.senderoption, "---Select One---", "@gmail.com", "@hotmail.com", "@yahoo.com")

        self.mail = tk.StringVar()
        self.mail.set("")
        self.textw = tk.Entry(self, textvariable=self.mail)

        button = tk.Button(self, text="Go to the start page",
                           command=lambda: controller.show_frame(StartPage))

        sendbutton = tk.Button(self, text = "Send Mail", command=self.sendmail)

        senderl.pack(side="top", anchor="w")
        rmail.pack(side="top", anchor="nw")
        senderdomain.pack(side="top", anchor="nw")
        self.textw.pack(fill="both")
        button.pack(side="bottom")
        sendbutton.pack(side="bottom")

    def sendmail(self):
        sent = tk.Label(self, text="Email has been sent")
        if self.senderoption.get() == "@gmail.com":
            try: 
                server.sendmail(self.v.get()+self.optionv.get(), self.reciever.get()+self.senderoption.get(), "YES")
                print("Success")
                sent.pack()
            except:
                print("Unsuccesful")
                print(PageOne.self.v.get())

if __name__ == "__main__":
    app = SampleApp()
    app.title("PyMail")
    app.geometry("400x400")
    app.mainloop()

StartPage中使用self.v,并从PageOnePageTwo中使用parent.v访问self.v - Kenly
2个回答

40

你的问题有一个简单的答案。 "如何从对象X获取值?" 对于任何对象,答案都相同:通过询问对象X来获得它。您所需要做的就是获取对该对象的引用,然后直接访问属性。

从其他页面访问数据

在您的情况下,PageTwo 中的代码需要引用 PageOne 才能获取变量 v

那么,如何获取引用?这段代码(无论是从教程还是从教程中复制的 stackoverflow answer)旨在使此过程更加容易。每个页面都被赋予控制器的引用,而此控制器则具有对每个页面的引用。因此,您可以请求控制器提供对页面的引用。

第一步是在每个类中保存对控制器的引用。有趣的是,您已经在 PageOne 中这样做了,但是您应该在所有页面中都这样做。确保您在每个 __init__ 方法中添加 self.controller = controller,像这样:

class PageTwo(tk.Frame):
    def __init__(self, parent, controller):
        ...
        self.controller=controller
        ...

接下来,我们需要在控制器类中添加一个方法,该方法将返回对页面的引用。请向 SampleApp 添加以下函数:

class SampleApp(tk.Tk):
    ...
    def get_page(self, page_class):
        return self.frames[page_class]
    ...

现在,从任何“页面”内部,您都可以访问任何其他“页面”的对象。例如,在 PageTwo 中,您可以像这样从 PageOne 访问 v 变量:

page1 = self.controller.get_page(PageOne)
page1.v.set("Hello, world")

使用共享数据

更好的解决方案是让您的SampleApp类创建一组所有页面共享的变量。您可以在该类中创建一个字典,然后使用控制器来让每个页面都可以访问。例如:

class SampleApp(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        self.shared_data = {
            "username": tk.StringVar(),
            "password": tk.StringVar(),
            ...
        )

然后,在任何类中,您可以像这样访问数据:

entry1 = tk.Entry(self, textvariable=self.controller.shared_data["username"])
...
username = self.controller.shared_data["username"].get()
这是更好的解决方案的原因在于您的页面不需要知道其他页面的实现方式。当一个页面依赖于另一个页面的确切实现时,这被称为“紧耦合”。如果页面不需要知道其他页面的实现方式,则称为“松耦合”。
松散的耦合给您带来更多的灵活性。每个页面不再与所有其他页面紧密耦合,而是都与一个单一的对象(即控制器)紧密耦合。只要每个页面仅知道有关控制器的信息,就可以随时自由更改每个页面,而不会影响程序的其余部分。
当然,如果您更改控制器,则必须更改所有页面,但是如果您设计好了控制器,这种情况发生的可能性较小,并且管理起来更容易。

非常感谢您的帮助,我一直想知道“控制器”是什么,您在解释方面做得非常好。非常感谢。 - Supachai Abusali
2
@SupachaiAbusali:如果你找到了这个答案以及其他你提出的问题的答案,请考虑为它们投票和/或选择一个答案。请参见http://stackoverflow.com/help/someone-answers。 - Bryan Oakley
1
你好,能否帮忙回答一下关于tkinter的问题?我已经尝试了几个小时但是没有成功。 https://stackoverflow.com/questions/53942023/passing-variable-from-one-window-to-another-in-tkinter - Yunus

-1

这与全局框架有关。

如果您在类内部创建变量,则该变量仅存在于该函数内部。如果您想将类(或函数)内的变量“传输”到全局框架中,则使用global

class firstClass():
    global my_var_first
    my_var_first = "first variable"

print(my_var_first) # This will work, because the var is in the global frame

class secondClass():
    my_var_second = "second variable"
    print(my_var_first) # This will work, as the var is in the global frame and not defined in the class

print(my_var_second) # This won't work, because there is no my_var_second in the global frame

为了可视化内存,您可以使用pythontutor,它会逐步展示内存是如何创建的。

希望我能帮到你!

编辑

我认为我应该补充一下,如果你在类/函数内部定义了一个与全局框架中变量同名的变量,它不会删除全局变量。相反,它将在自己的框架中创建一个新的变量(具有相同的名称)。如果可用,类或函数将始终使用其自己框架中的变量。

x = 5
def print_variable():
    x = 3
    print(x)
print(x)
print_variable()

# OUTPUT:
# 5
# 3

3
原文:The question as written has nothing to do with the global frame. Using globals is a workaround, but it's not a proper fix.翻译:这个问题与全局框架没有任何关系。使用全局变量只是一种权宜之计,而不是正确的解决方法。 - Bryan Oakley
@MartijnLuyckx 感谢您的建议,但在发布问题之前我已经尝试过了,似乎并没有起作用。 - Supachai Abusali
@SupachaiAbusali 这确实很奇怪!很抱歉我无法提供帮助。 - Martijn Luyckx
1
Martijn:全局变量通常被认为是一种不良的编程实践(请参见为什么全局变量邪恶?为什么全局状态邪恶?),我认为应该避免使用它们。你们大学的计算机科学专业没有教这个吗? - martineau
1
@martineau 当我发布这个答案(4年前)时,我只上了两个月的大学。他们确实教授编程实践,但我必须先掌握基础知识(当时我仍在做这件事)。我绝对没有能力正确和全面地回答这个问题,但由于不知道我还不知道的东西,所以当时我并不知道。 - Martijn Luyckx
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接