在tkinter中,是否可以将同一小部件​​放置在多个框架中?

时间:2018-09-03 15:12:28

标签: python tkinter

我有一个带有ttk.Notebook选项卡的UI,并且希望在多个选项卡中显示相同的窗口小部件。这要求小部件同时具有多个父框架,这似乎是不可能的。还有其他方法可以完成吗?

2 个答案:

答案 0 :(得分:0)

否,您不能在多个地方使用单个窗口小部件。一个小部件一次只能位于一个位置。

答案 1 :(得分:0)

此后,我一直在解决这个问题,并提出了这个初步的(且未经测试)的解决方案,使Widget出现在ttk.Notebook的多个选项卡上。

尽管在创建小部件时会不变地设置其物理父级,但可以使用.grid()in_选项更改其几何父级(控制其显示位置)。因此,从理论上讲,只要用户更改为新标签(NotebookTabChanged),只需更改其几何父项,就可以使该小部件出现在多个笔记本标签上

下面的代码似乎可以像宣传的那样工作,尽管我还没有在下面的玩具代码之外进行真正的测试:

import tkinter as tk
import tkinter.ttk as ttk

class myApp(tk.Tk):

    def __init__(self):

        super().__init__()

        # Create the Notebook and bind the tab-select event 
        self.notebook = ttk.Notebook(self, width=500, height=200)
        self.notebook.grid()
        self.notebook.bind("<<NotebookTabChanged>>", self.select_tab)

        # Create a status bar which displays the name of the currently selected tab 
        self.status = ttk.Label(self)
        self.status.grid(sticky='w')

        # Create three frames - one for each of three tabs - and store them in 
        # a dictionary with the tab names as keys
        self.tabs = dict()
        self.tabs['PAGE 1'] = ttk.Frame(self.notebook)
        self.tabs['PAGE 2'] = ttk.Frame(self.notebook)
        self.tabs['PAGE 3'] = ttk.Frame(self.notebook)

        # Create the tabs in the notebook
        for t in self.tabs.keys():
            self.notebook.add(self.tabs[t], text=t, underline=0, sticky='nsew')

        # Put a widget on the middle tab, just to have soemthing there
        ttk.Label(self.tabs['PAGE 2'],text="A SIMPLE LABEL").grid(row=0,column=0)

        # Create a button - this is the widget we wish to appear on all tabs
        self.btn = tk.Button(self,text='PRESS ME!',command=self.button_pressed)


    # This is the method called when the user selectes a new tab. It 
    # updates the status bar and moves the button to the new tab.

    def select_tab(self, event):
        id = self.notebook.select()
        name = self.notebook.tab(id, "text")
        text = f"--- {name} is currently selected ---"
        self.status.config(text=text)
        self.btn.grid(row=4,column=0,in_= self.tabs[name])


    def button_pressed(self):
        print('BUTTON PRESSED')


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