python - 将参数传递给 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'
对初学者/中级的任何帮助将不胜感激!
解决方案
您(以及似乎 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()
。
推荐阅读
- java - 与 netty 相比,为什么下面的 Java NIO API 这么慢
- reactjs - ExpressJS 的 React Cors 问题
- ruby-on-rails - # 未定义的方法“图像”
我正在尝试使用 DropzoneJS 和 Active Storage 实现照片上传,但此时,我的应用程序抛出
undefined method 'image' for #<ActiveStorage::Attachment:0x00007fa51201dd80>
错误。python-3.x - 从函数返回 memoryview 是否安全?
- cluster-computing - 访问由流量管理器管理的特定 Azure 应用服务
- excel - 如果满足特定要求,则在循环中插入额外的行
- java - 如何从edittext获取给定年份的第三个星期三?
- node.js - forEach 函数不等待在 AWS lambda 上返回缓冲区
- c# - 对 Azure Devops Git 存储库进行身份验证
- jasper-reports - 元素 jr:jrxml 文件中不允许使用表