简体   繁体   中英

How do I reference my Tkinter "root" instance from within another class?

I am using the below code to create a window and raise different frames around. I need to create a toplevel, but I am trying to make the Toplevel window appear within the bounds of the main window. Looking around on here, I am finding the way to do this is to use wm_transient(root). The problem is my "root" is called app, and its not accessible from within the class where I am calling these functions.

So my popup function I am calling, I am trying to make my popup (toplevel) have the attribute of wm_transient, but I have to set the master to root (app in my application) and cannot figure out how to make this work.

So my underlying question is how to make the toplevel appear within the bounds of my main window, but what I would really like to know is how to make calls/reference my root window.

import tkinter as tk

class APP1(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        self.title('APP')
        self.geometry("552x700")
        self.resizable(False, False)

        container = tk.Frame(self)
        container.pack(side="top", fill="both", expand=True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)

        self.frames = {}

        self.frames["MenuPage"] = MenuPage(parent=container, controller=self)
        self.frames["MenuPage"].grid(row=0, column=0, sticky="nsew")
        self.show_frame("MenuPage")

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

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

        def popup():
            x = tk.Toplevel(self)
            x.wm_transient(app)

        template = tk.Button(self, text='Popup', height=3, width=20, bg='white', font=('12'), command=lambda: popup())
        template.pack(pady=50)


if __name__ == "__main__":
    app = APP1()
    app.mainloop()

In your specific example you already have two ways to access your "root".

First, your root is app , the instance of APP1 , and it's a global variable so it is already available everywhere. It's global because you define it outside the context of a function or class.

Second, you pass the instance of APP1 as the controller parameter in your MenuPage class. You're saving that as self.controller , so anywhere you need the instance of APP1 you can use self.controller .

For more help understanding the code you've copied, see Switch between two frames in tkinter which contains links to many questions that have been asked about this code.

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