简体   繁体   中英

How can I pass variables from one Tkinter window to another?

I'm using Tkinter in Python to create a planner. I'm trying to figure out how to pass variables from one window/class to another, using Tkinter buttons. For example, how do I introduce the string variable 'user_input' in 'StartPage' to the 'CalendarToday' window. The button that directs the user to the 'CalendarToday' page from the start page is 'btn_today'. Is there any way to make this button pass the user_input variable to the 'CalendarToday' class?

class SampleApp(tk.Tk):

    def __init__(self):
        tk.Tk.__init__(self)
        self._frame = None
        self.switch_frame(StartPage)

    def switch_frame(self, frame_class):
        #variable = None
        new_frame = frame_class(self)
        if self._frame is not None:
            self._frame.destroy()
        self._frame = new_frame
        self._frame.pack()

class StartPage(tk.Frame):

    def __init__(self, master):
        tk.Frame.__init__(self, master)

        master.title("My Calendar")

        tk.Label(self, text="My Calendar!", font=('Helvetica', 16, "bold")).grid(row = 1, column = 2, pady = 35)

        # Today's Calendar button
        btn_today = tk.Button(self, text="Today's Calendar", width = 20, height = 3, command=lambda: master.switch_frame(Calendar_Today))
        btn_today.grid(row = 3, column = 2, pady = 40, padx = 60)

        # Entry Form
        entry_form = tk.Entry(self)
        entry_form.insert(0, 'Month, Year')
        # user_input is the string variable holding the the user's input of month and year.
        user_input = entry_form.get()
        print(user_input)
        entry_form.grid(row = 4, column = 2, pady = 0)

        # Specify Calendar button
        btn_specify = tk.Button(self, text="Specify month",width = 20, height = 3,command=lambda: master.switch_frame(PageTwo))
        btn_specify.grid(row = 5, column = 2, pady = 10)

        # Quit button
        btn_quit = tk.Button(self, text="Quit App",width = 20, height = 3,command=master.destroy)
        btn_quit.grid(row = 6, column = 2, pady = 20)
        

class Calendar_Today(tk.Frame):
    def __init__(self, master):

        month_display = month_today + " " + year_today

        tk.Frame.__init__(self, master)
        master.title(month_display)
        
        lbl_display = tk.Label(self, text= month_display)
        lbl_display.grid(row = 1, column = 2)

        btn_date1 = tk.Button(self, text="Dates", width =  4, height = 2)
        btn_date1.grid(row = 3, column = 2, padx = 10, pady = 10)

        ########################################
        
        btn_next = tk.Button(self, text="Next Month")
        btn_next.grid(row = 8, column = 1, padx = 10, pady = 10)
        
        btn_previous = tk.Button(self, text="Previous Month")
        btn_previous.grid(row = 8, column = 2, padx = 10, pady = 10)
        
        btn_return = tk.Button(self, text="Return to Menu",command=lambda: master.switch_frame(StartPage))
        btn_return.grid(row = 8, column = 3, padx = 10, pady = 10)

if __name__ == "__main__":
    app = SampleApp()
    app.title("My Calendar!")
    app.mainloop()

You can modify switch_frame() to accept optional arguments and pass these arguments to page classes:

from tkinter import messagebox
...

class SampleApp(tk.Tk):
    ...

    def switch_frame(self, frame_class, *args, **kw): # added optional arguments
        if self._frame:
            self._frame.destroy()
        self._frame = frame_class(self, *args, **kw)  # pass optional arguments to frame class
        self._frame.pack()

class StartPage(tk.Frame):
    def __init__(self, master):
        ...
        # Today's Calendar button
        btn_today = tk.Button(self, text="Today's Calendar", width=20, height=3,
                              command=self.show_calendar)
        btn_today.grid(row=3, column=2, pady=40, padx=60)
        ...

    def show_calendar(self):
        user_input = self.entry_form.get().strip()
        tokens = user_input.split()
        # make sure month and year are specified
        # need to do some other validations to make sure valid month and year are input
        if len(tokens) == 2:
            # pass the user input to Calendar_Today class
            self.master.switch_frame(Calendar_Today, *tokens)
        else:
            messagebox.showerror("Error", f"Invalid input: {user_input}")

class Calendar_Today(tk.Frame):
    def __init__(self, master, month_today, year_today):  # added month and year arguments
        ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM