首页 > 解决方案 > 将参数传递给 TkInter 帧

问题描述

我是一名教师,每周我都会对学生的参与分数进行评分。自从我教计算机以来,我想我会创建一个程序来为我处理该逻辑。我计划使用 TkInter 创建一个包含一天中 4 个时段的开始屏幕,并且根据时段,它会拉起该类。但我试图在所有 4 个时期都使用同一个类,因为代码完全相同。

这是我的代码:

class part(tk.Tk):
    #Creates a class for the GUI

    def __init__(self, *args, **kwargs):
        #Initialization function of partGUI
        tk.Tk.__init__(self, *args, **kwargs)

        tk.Tk.iconbitmap(self, default="") #default icon in an .ico file
        tk.Tk.wm_title(self, "Lucey's Participation Program") #title

        window = tk.Frame(self)
        window.pack(side="top", fill="both", expand=True)
        window.grid_rowconfigure(0, weight=1)
        window.grid_columnconfigure(0, weight=1)

        self.frames= {}



        for F in (StartPage, ClassPart, SettingsPage):
            frame = F(window, self)
            self.frames[F] = frame
            frame.grid(row=0, column=0, sticky="nsew")

        self.show_frame(StartPage)

    def show_frame(self, window):
        #Allows Program to switch windows/pages/frames
        frame = self.frames[window]
        frame.tkraise()

class StartPage(tk.Frame):
# Home Screen for Program
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        title = tk.Label(self, text="Participation Scores", font=LARGE_FONT)
        title.pack(pady=10, padx=10)

        btnPeriod1 = tk.Button(self, text="1st Period", fg="red",
                               command=lambda: controller.show_frame(ClassPart(controller, 1)))
        btnPeriod1.pack()


class ClassPart(tk.Frame):
# Screen showing students, participation buttons & their scores/Hogwarts houses    

    def __init__(self, parent, controller, period):
        tk.Frame.__init__(self, parent)

但这会引发错误:

Traceback (most recent call last):
  File "/home/klucey/Documents/partvers2.py", line 307, in <module>
    window = part()
  File "/home/klucey/Documents/partvers2.py", line 40, in __init__
    frame = F(window, self)
TypeError: __init__() missing 1 required positional argument: 'period'

对初学者/中级的任何帮助将不胜感激!

标签: pythontkinter

解决方案


您(以及似乎 SO 上的其他所有人)用来处理多页 Tkinter 应用程序的这个样板代码根本不适合处理同一类的多个页面。您必须ClassPart在页面列表中多次出现 of,并以某种方式安排它们period在构造时被赋予不同的参数 - 但这会破坏.show_frame()方法,因为您不再有唯一标识符来选择要显示的页面。

鉴于您有一组固定的页面(这不适用于动态生成的页面),这是我的建议:

  • 去掉period类中的参数(以便其构造函数与其他页面兼容)。
  • 为每个时期创建它的子类:

    class ClassPart1(ClassPart):
        period = 1
    class ClassPart2(ClassPart):
        period = 2
    

    ... 等等。在基类中引用以self.period访问此值。

  • 将初始页面创建循环更改为for F in (StartPage, ClassPart1, ClassPart2, ClassPart3, ClassPart4, SettingsPage):. 使用ClassPart1等作为要传递给 的标识符.show_frame()


推荐阅读