在 tkinter 中添加笔记本选项卡 - 如何使用基于类的结构来完成?(蟒蛇 3)

Pla*_*ave 2 python tkinter python-3.x

我写了一个 tkinter 应用程序,它在两个框架上显示了小部件,类似于这个例子,它成功运行。

from tkinter import *
from tkinter import ttk

root = Tk()
root.title("Example")

notebook = ttk.Notebook(root)
frame1 = ttk.Frame(notebook)
frame2 = ttk.Frame(notebook)
notebook.add(frame1, text="Frame One")
notebook.add(frame2, text="Frame Two")
notebook.pack()

#(The labels are examples, but the rest of the code is identical in structure). 

labelA = ttk.Label(frame1, text = "This is on Frame One")
labelA.grid(column=1, row=1)

labelB = ttk.Label(frame2, text = "This is on Frame Two")
labelB.grid(column=1, row=1)

root.mainloop()
Run Code Online (Sandbox Code Playgroud)

我决定我应该尝试重组程序以使用一个类(我承认我不是很熟悉)。但是,我不确定我应该怎么做才能让小部件出现在不同的框架上(其他一切正常)。例如,下面会产生一个“TypeError: init () 需要 1 到 2 个位置参数,但给出了 3 个。” 所以大概我需要用一个额外的参数来初始化,但我不确定笔记本将如何工作,或者这是否是我应该采取的方法。(如果从标签中删除“frame1”和“frame2”参数,程序将运行,但是,它会在两个框架上显示相同的内容)。

from tkinter import *
from tkinter import ttk

class MainApplication(ttk.Frame):
    def __init__(self, parent):
        ttk.Frame.__init__(self, parent)

        self.labelA = ttk.Label(self, frame1, text = "This is on Frame One")
        self.labelA.grid(column=1, row=1)

        self.labelB = ttk.Label(self, frame2, text = "This is on Frame Two")
        self.labelB.grid(column=1, row=1)

root = Tk()
root.title("Example")
notebook = ttk.Notebook(root)
frame1 = ttk.Frame(notebook)
frame2 = ttk.Frame(notebook)
notebook.add(frame1, text="Frame One")
notebook.add(frame2, text="Frame Two")
notebook.pack()
MainApplication(root).pack()
root.mainloop()
Run Code Online (Sandbox Code Playgroud)

我对解决方案感兴趣,但我也有兴趣了解与独立小部件相比,该类在做什么。

Mar*_*nen 5

This would be one way to generalize the application as a class. You want to eliminate the repeated code.

from tkinter import *
from tkinter import ttk

class Notebook:

    def __init__(self,title):
        self.root = Tk()
        self.root.title(title)
        self.notebook = ttk.Notebook(self.root)

    def add_tab(self,title,text):
        frame = ttk.Frame(self.notebook)
        self.notebook.add(frame,text=title)
        label = ttk.Label(frame,text=text)
        label.grid(column=1,row=1)
        self.notebook.pack()

    def run(self):
        self.root.mainloop()

nb = Notebook('Example')
nb.add_tab('Frame One','This is on Frame One')
nb.add_tab('Frame Two','This is on Frame Two')
nb.run()
Run Code Online (Sandbox Code Playgroud)