我正在使用tkinter为我用Python2.7编写的程序创建UI。我修改了我在此处找到的代码:Switch between two frames in tkinter
我遇到了跨实例传递变量的问题。当我将page1
参数添加到类__init__
中的page2
方法时,会返回以下错误消息:
追踪(最近一次呼叫最后一次):
文件“question.py”,第77行,(模块)
app =设置()
文件“question.py”,第16行,在_ init _
中frame = F(parent = container,controller = self)
TypeError:_ init _()需要4个参数(给定3个)
以下是我的代码的简化版本:
import Tkinter as tk
class Setup(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
container = tk.Frame(self)
container.pack(side="top", fill="both", expand=True)
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
self.frames = {}
for F in (page1, page2):
page_name = F.__name__
frame = F(parent=container, controller=self)
self.frames[page_name] = frame
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame("page1")
def show_frame(self, page_name):
frame = self.frames[page_name]
frame.tkraise()
class page1(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
tk.Label(self, text="Number of children:").grid(row=2, sticky=tk.E)
self.ChildrenNo = tk.Entry(self)
self.ChildrenNo.grid(row=2, column=1)
Quit = tk.Button(self, text="Exit", command= self.quit)
Quit.grid(row=13, column=0, sticky="sw")
Next = tk.Button(self, text="OK",
command=lambda: controller.show_frame("page2"))
Next.grid(row=13, column=1, sticky=tk.SE)
Apply = tk.Button(self, text="Apply", command = self.varset1)
Apply.grid(row=13, column=1, sticky=tk.SW)
self.childno = 0
self.rowno = 0
def varset1(self):
self.childrenno = self.ChildrenNo.get()
class page2(tk.Frame):
def __init__(self, parent, controller, page1):
tk.Frame.__init__(self, parent)
self.controller = controller
self.childrenno = page1.childrenno
for i in range(self.childrenno):
self.childno = self.childno + 1
self.rowno = self.rowno + 1
tk.Label(self, text="Age of child %r:" % (self.childno)).grid(row=2, sticky=tk.E)
self.ChildrenNo = tk.Entry(self)
self.ChildrenNo.grid(row=self.rowno, column=1)
Quit = tk.Button(self, text="Exit", command= self.quit)
Quit.grid(row=13, column=0, sticky="sw")
Back = tk.Button(self, text="Back",
command=lambda: controller.show_frame("page1"))
Back.grid(row=13, column=1, sticky=tk.SE)
Apply = tk.Button(self, text="Apply", command = self.varset2)
Apply.grid(row=13, column=1, sticky=tk.SW)
def varset2(self):
houseno = self.HouseNo.get()
postcode = self.PostCode.get()
if __name__ == "__main__":
app = Setup()
app.mainloop()
我哪里可能出错?提前感谢您的帮助。