在Tkinter中的帧之间传递变量

时间:2017-09-11 15:25:25

标签: python tkinter

所以基本上我有2个帧,UploadPage和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中显示它。我怎么做?谢谢!

1 个答案:

答案 0 :(得分:0)

您基本上需要PageOne实例才能知道UploadPage实例。 为此,您可以将后者作为参数传递给前者的__init__方法:

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

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

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

当然,您需要controllerUploadPage作为参数传递给PageOne.__init__

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