簡體   English   中英

如何從另一個 class 中引用我的 Tkinter“根”實例?

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

我正在使用下面的代碼創建一個 window 並提高不同的框架。 我需要創建一個頂層,但我試圖讓頂層 window 出現在主 window 的范圍內。 環顧四周,我發現這樣做的方法是使用 wm_transient(root)。 問題是我的“根”被稱為應用程序,它不能從我調用這些函數的 class 中訪問。

因此,我正在調用我的彈出窗口 function,我試圖使我的彈出窗口(頂層)具有 wm_transient 的屬性,但我必須將 master 設置為 root(我的應用程序中的應用程序)並且無法弄清楚如何使它工作。

所以我的基本問題是如何使頂層出現在我的主要 window 的范圍內,但我真正想知道的是如何調用/引用我的根 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()

在您的具體示例中,您已經有兩種訪問“root”的方法。

首先,您的根是app ,即APP1的實例,它是一個全局變量,因此它已經在任何地方都可用。 它是全局的,因為您在 function 或 class 的上下文之外定義它。

其次,將APP1的實例作為controller參數傳遞到MenuPage class 中。 您將其保存為self.controller ,因此任何需要APP1實例的地方都可以使用self.controller

有關了解您復制的代碼的更多幫助,請參閱在 tkinter 中的兩個幀之間切換,其中包含許多有關此代碼的問題的鏈接。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM