在 Tkinter 中的帧之间传递变量 [英] Passing variables between frames in Tkinter

查看:29
本文介绍了在 Tkinter 中的帧之间传递变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以基本上我有 2 个框架,UploadPage 和 PageOne:

So basically I have 2 frames, UploadPage and PageOne:

class UploadPage(tk.Frame):


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




    theLabel = tk.Label(self, text='Upload your CSV here.', padx=10, pady=10)
    theButton = tk.Button(self, text='Browse', command=open_file)
    fileLabel = tk.Label(self, padx=10, pady=10)
    submitButton = tk.Button(self, text='Submit', command= lambda: controller.show_frame(PageOne))
    filePathLabel = tk.Label(self) #hidden label used to store file path
    theLabel.grid(row=0)
    theButton.grid(row=1, column=0)
    fileLabel.grid(row=1, column=1)
    submitButton.grid(row=3, column=0)

class PageOne(tk.Frame):

def __init__(self, parent, controller):
    tk.Frame.__init__(self, parent)
    self.controller = controller
    theLabel = tk.Label(self, text='Hi', padx=10, pady=10)
    theLabel.pack()
app = SeeAssBeeapp()
app.mainloop()

说我想在 UploadPage 中获取 filePathLabel 的文本并在 PageOne 中显示它.我怎么做?谢谢!

Say I want to get the text of filePathLabel in UploadPage and display it in PageOne. How do i do that? Thank you!

推荐答案

您基本上需要 PageOne 实例来了解 UploadPage 实例.为此,您可以例如将后者作为参数传递给前者的 __init__ 方法:

You basically need the PageOne instance to know of the UploadPage instance. For that purpose, you can for instance pass the latter as parameter to the former's __init__ method:

def __init__(self, parent, controller, uploadPage=None):
    self.uploadPage = uploadPage
    ...

现在您可以从 PageOne 实例访问 filePathLabel:

Now you can access filePathLabel from the PageOne instance:

if self.uploadPage is not None:
    self.uploadPage.filePathLabel

当然,您需要 controller 将该 UploadPage 作为参数传递给 PageOne.__init__:

Of course, you will need controller to pass that UploadPage as parameter to PageOne.__init__:

# controller
myUploadPage = UploadPage(...)
myPageOne = PageOne(parent, controller, uploadPage=myUploadPage)

这篇关于在 Tkinter 中的帧之间传递变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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