如何在 tkinter for python 中保存共享数据? [英] How to save shared data in tkinter for python?

查看:38
本文介绍了如何在 tkinter for python 中保存共享数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对使用 Python 的 GUI 世界非常陌生,并试图用多个页面构建我的第一个 GUI,但从输入框中共享变量确实让我陷入了循环.我知道代码可能有很多错误,但就目前而言,我真的只想更好地了解如何从用户名输入框中共享页面之间的变量.

I'm very new to the world of GUIs with Python and attempting to build my first one with multiple pages, but sharing a variable from an entry box is really throwing me through a loop. I understand there's probably a lot wrong with the code, but for now, I would really just like to better understand how to share the variables between the pages from the username entry box.

这是与此相关的代码:(分页符只是存在一些不相关代码的地方)

Here is the code that ties into this:(The page breaks are just where there is some unrelated code)

import tkinter as tk
from tkinter import Tk, Label, Button, StringVar

class Keep(tk.Tk):

    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        self.shared_data ={
            "email": tk.StringVar(),
            "password": tk.StringVar()
        }
# Skipping some code to get to the good stuff

class StartPage(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        # LABELS, ENTRIES, AND BUTTONS

        # page break

        self.entry1 = tk.Entry(self, textvariable=self.controller.shared_data["email"])
        entry2 = tk.Entry(self, show = '*')
        button1 = tk.Button(text="Submit", command=lambda: [controller.show_frame("PageTwo"), self.retrieve()])

    # page break

    def retrieve(self):
        self.email = self.controller.shared_data["email"].get()
        self.controller.email = self.email

class PageTwo(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        self.email = self.controller.shared_data["email"].get()

        label1 = tk.Label(self, text="Welcome, {}".format(self.email))

if __name__ == "__main__":
    keep = Keep()
    keep.mainloop()

我知道检索功能看起来很时髦,可能根本不正确,但我已经研究这个特定问题大约一个星期了,它让我陷入了一些疯狂的兔子洞.

I know the retrieve function looks pretty funky and probably not at all correct, but I've been working on this specific problem for about a week now and it has lead me down some wild rabbit holes.

最终目标是让 pageTwolabel1 显示欢迎,(插入在 entry1 中输入的电子邮件起始页)".

The end goal is for label1 of pageTwo to display, "Welcome, (insert e-mail entered in entry1 of startPage)".

我认为我的问题在于 pageTwoshared_data 检索空字符串,但我不明白为什么会这样.

I think my issue lies with pageTwo retrieving an empty string from shared_data, but I don't understand why that is.

非常感谢任何帮助!

推荐答案

我想问题是因为框架是在 Keep.__init__ 中创建的,而不是在您运行 show_frame() 时>,所以 PageTwo.__init__() 在开始时执行,文本 Welcome... 在开始时创建 - 在您甚至看到 StartPage 之前.

I guess problem is because frames are created in Keep.__init__, not when you run show_frame(), so PageTwo.__init__() is executed at start and text Welcome... is create at start - before you even see StartPage.

您应该在 __init__ 中创建空标签,并在其他方法(即 update_widgets())中创建文本 Welcome...将在 show_frame()show_frame() 内的事件之后执行,如果所有类都有 update_widgets()>

You should create empty label in __init__ and create text Welcome... in other method (ie. update_widgets()) which you will execute after show_frame() or event inside show_frame() if all classes will have update_widgets()>

最少的工作代码:

import tkinter as tk


class Keep(tk.Tk):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.shared_data ={
            "email": tk.StringVar(),
            "password": tk.StringVar()
        }

        self.frames = {
            'StartPage': StartPage(self, self),
            'PageTwo': PageTwo(self, self),
        }

        self.current_frame = None
        self.show_frame('StartPage')

    def show_frame(self, name):
        if self.current_frame:
            self.current_frame.forget()
        self.current_frame = self.frames[name]
        self.current_frame.pack()

        self.current_frame.update_widgets() # <-- update data in widgets


class StartPage(tk.Frame):

    def __init__(self, parent, controller):
        super().__init__(parent)
        self.controller = controller

        self.entry1 = tk.Entry(self, textvariable=self.controller.shared_data["email"])
        self.entry1.pack()
        entry2 = tk.Entry(self, show='*')
        entry2.pack()
        button = tk.Button(self, text="Submit", command=lambda:controller.show_frame("PageTwo"))
        button.pack()

    def update_widgets(self):
        pass

class PageTwo(tk.Frame):

    def __init__(self, parent, controller):
        super().__init__(parent)
        self.controller = controller

        self.label = tk.Label(self, text="") # <-- create empty label
        self.label.pack()

    def update_widgets(self):
        self.label["text"] = "Welcome, {}".format(self.controller.shared_data["email"].get()) # <-- update text in label


if __name__ == "__main__":
    keep = Keep()
    keep.mainloop()

这篇关于如何在 tkinter for python 中保存共享数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆