TKInter GUI外观包含笔记本更改时,我更改类名,但不更改参数



我正试图用Notebook选项卡制作应用程序,但每个选项卡都应该作为类单独描述。一开始,我为两个选项卡提供了两个类名,分别为Frame1和Frame2,但我想给出合理的名称。以下是有效的代码:

from tkinter import *
from tkinter import ttk
root = Tk()
root.geometry('400x400')
root.title('Title')
notebook = ttk.Notebook(root)
class Frame1(Frame):
def __init__(self, container):
super().__init__(container)
self.Frame1 = Frame(container)
self.Frame1.config(bg='blue')
self.Frame1.place(x=0, y=24, relwidth=0.9, relheight=0.9)

class Frame2(Frame):
def __init__(self, container):
super().__init__(container)
self.Frame2 = Frame(container)
self.Frame2.config(height=200, width=203, bg= 'green')
self.Frame2.place(x=0, y=24)
Frame1 = Frame1(notebook)
notebook.add(Frame1, text = "Connection")
Frame2 = Frame2(notebook)
notebook.add(Frame2, text = "Transient Response")
notebook.place(x=10, y=10)
root.mainloop()

结果显示在屏幕截图上-2个蓝色和绿色填充的选项卡。我想给出合理的名字。一旦我更改类名,例如Frame2改为Frame3,图片就会损坏(见屏幕截图(。

您不应该在框架类中创建框架。Frame1Frame2的实例已经是帧。如果确实在Frame1Frame2内部添加了一个帧,则它们需要是self的子级,而不是container

此外,您使用名称Frame1作为类的名称和实例。你不应该那样做。根据PEP8,您应该使用小写的第一个字母来命名实例。

class Frame1(Frame):
def __init__(self, container):
super().__init__(container, bg='blue')
frame1 = Frame1(notebook)

注意,Frame1的实例本身就是一个帧,就像任何其他帧一样。如果你想配置任何属性,你可以像我的例子一样,在调用super时设置背景,但你也可以随时在self上调用configure方法:

class Frame1(Frame):
def __init__(self, container):
super().__init__(container, bg='blue')
self.configure(width=200, height=200)

您也可以像使用任何其他小部件一样在类外配置它:

frame1 = Frame1(notebook)
...
frame1.configure(background="bisque")

最新更新