用户输入不显示在下一页上

时间:2019-07-16 19:37:05

标签: python tkinter

我正在编写一个程序,该程序最终将要求用户输入文件名并图形化数据文件。但是,我很难将用户输入的文件名传输到下一页。

我已经实现了本页(How to access variables from different classes in tkinter?)上显示的两个答案,但是很遗憾,这个答案无法起作用。我在想也许PageOne正在被重写,或者entry_field_variable正在被重写或未保存。我是tkinter的新手,因此我可能会进行明显的疏忽,但我们将为您提供任何帮助。

import tkinter as tk


LARGE_FONT= ("Verdana", 12)
NORM_FONT= ("Verdana", 10)
SMALL_FONT= ("Verdana", 8)


class mGui(tk.Tk):  


    def __init__(self, *args, **kargs): 

       tk.Tk.__init__(self, *args, **kargs) 
       container = tk.Frame(self)
       container.grid_rowconfigure(0, weight=1)
       container.grid_columnconfigure(0, weight=1)
       container.grid()



       self.shared_data = {"entry_field_variable":tk.StringVar()}

       self.frames = {}  

       for F in (StartPage, PageOne):

            frame = F(container, self)

            self.frames[F] = frame
            frame.grid(row=0, column=0, sticky="nsew")



       self.show_frame(StartPage)   

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


class StartPage(tk.Frame):  

    def __init__(self, parent, controller):  
        self.controller = controller
        tk.Frame.__init__(self, parent) 
        label_1 = tk.Label(self, text = "Start Page", font = LARGE_FONT)
        label_1.grid(row = 0, column = 0)


        entry1 = tk.Entry(self, textvariable = self.controller.shared_data["entry_field_variable"])
        entry1.grid(row = 1, column = 0)




        button1 = tk.Button(self,text = "Go", command = lambda: controller.show_frame(PageOne))
        button1.grid(row = 2, column = 0) 



class PageOne(tk.Frame):  

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

        label_1 = tk.Label(self, text = "Page One", font = LARGE_FONT)
        label_1.grid(row = 1, column = 4)  

        filename = self.controller.shared_data["entry_field_variable"].get()


        label_2 = tk.Label(self, text = filename, font = LARGE_FONT)
        label_2.grid(row = 2, column = 0)

        button1 = tk.Button(self, text = "Go Back", command = lambda: controller.show_frame(StartPage))
        button1.grid(row = 4, column = 1)              


app = mGui()
app.mainloop()

1 个答案:

答案 0 :(得分:0)

您使用tk.StringVar的想法很好,但是您缺少一些东西:

  • 您需要收集在entry的{​​{1}}字段中输入的值。
  • 此值需要传递到控制器。
  • 最后,StartPage必须有权访问它,因此有必要将保存文件名的PageOne分配给标签tk.StringVar

这是可以完成的方法:

textvariable