一个小部件一次只能出现在一个位置.如果不在活动选项卡更改时将其从一个选项卡中移除并将其添加到另一个选项卡中,则无法在多个笔记本选项卡之间共享框架.
如果这就是您想要做的,您可以创建一次"Runbox",然后在每个选项卡中添加一个容器作为占位符.您可以向<Visibility>
事件添加绑定,以便在占位符变为可见时将Runbox添加到占位符.
这可能会在您切换选项卡时导致一些闪烁.
要做到这一点,关键是使用pack
的in_
参数,它允许您将一个小部件打包到另一个小部件中.它还使用lift
机制来确保"Runbox"在z顺序上高于占位符.只要Runbox的可见性发生变化,就会通过绑定到<Visibility>
事件来重新打包.
这里有一个例子.它创建一个Runbox
的实例,并在两个选项卡之间交换它.
import tkinter as tk
from tkinter import ttk
class RunParameters():
"""Parameters to be shared by all tabs"""
def __init__(self):
self.magic_num = tk.IntVar(value=0)
self.iter_count = tk.IntVar(value=1)
self.duration = tk.IntVar(value=0)
self.result = "fail"
self.repeat = tk.BooleanVar(value=True)
class Runbox(tk.Frame):
def __init__(self, parent, run_parameters):
super().__init__(parent)
radiobuttons = []
for i in (range(8)):
rb = tk.Radiobutton(
self, text=i, variable=run_parameters.magic_num, value=i
)
radiobuttons.append(rb)
itercount_spinbox = tk.Spinbox(
self, from_=1, to=100,
textvariable=run_parameters.iter_count
)
duration_spinbox = tk.Spinbox(
self, from_=0, to=100,
textvariable=run_parameters.duration
)
radiobuttons[0].grid(row=0, column=0)
radiobuttons[1].grid(row=0, column=1)
radiobuttons[2].grid(row=0, column=2)
radiobuttons[3].grid(row=0, column=3)
radiobuttons[4].grid(row=1, column=0)
radiobuttons[5].grid(row=1, column=1)
radiobuttons[6].grid(row=1, column=2)
radiobuttons[7].grid(row=1, column=3)
itercount_spinbox.grid(row=3, column=0, columnspan=4)
duration_spinbox.grid(row=4, column=0, columnspan=4)
class TestInfo(tk.Frame):
def __init__(self, parent, runbox):
super().__init__(parent)
self.runbox = runbox
self._container = tk.Frame(self)
label = tk.Label(self, text="Something unique to the Test Info tab")
self._container.pack(side="top", fill="x")
label.pack(side="bottom", fill="both", expand=True)
self.bind("<Visibility>", self.on_vis)
def on_vis(self, event):
if self.winfo_viewable():
self.runbox.pack(in_=self._container, fill="both", expand=True)
self.runbox.lift()
class TestList(tk.Frame):
def __init__(self, parent, runbox):
super().__init__(parent)
self.runbox = runbox
self._container = tk.Frame(self)
listbox = tk.Listbox(self)
listbox.insert("end", "Test 1", "Test 2", "Test 3")
self._container.pack(side="top", fill="x")
listbox.pack(side="bottom", fill="both", expand=True)
self.bind("<Visibility>", self.on_vis)
def on_vis(self, event):
if self.winfo_viewable():
self.runbox.pack(in_=self._container, fill="both", expand=True)
self.runbox.lift()
class Trace32(tk.Frame):
pass
class TMEConfig(tk.Frame):
pass
root = tk.Tk()
params = RunParameters()
nb = ttk.Notebook(root)
nb.pack(fill="both", expand=True)
runbox = Runbox(nb, params)
test_info = TestInfo(nb, runbox = runbox)
test_list = TestList(nb, runbox = runbox)
trace32 = Trace32(nb)
tme_config = TMEConfig(nb)
nb.add(test_info, text="Test Info")
nb.add(test_list, text="Test List")
nb.add(trace32, text="Trace32")
nb.add(tme_config, text="TME config")
root.mainloop()