【发布时间】:2015-11-23 21:16:59
【问题描述】:
我在网上找到了一些代码来创建具有多个帧的 tkinter GUI。我尝试修改代码以包含一个带有导航按钮的框架,以显示在每个框架上,而不是每次都重复代码。我不断收到错误消息,无法弄清楚如何将导航按钮连接到相应的框架。 这是我得到的最接近的代码:
import Tkinter as tk
LARGE_FONT= ("Verdana", 12)
class SeaofBTCapp(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 (StartPage, PageOne, PageTwo):
frame = F(container, self)
self.frames[F] = frame
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame(StartPage)
def show_frame(self, cont):
frame = self.frames[cont]
frame.tkraise()
class StartPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self,parent)
label = tk.Label(self, text="Start Page", font=LARGE_FONT)
label.pack(pady=10,padx=10)
button = tk.Button(self, text="Visit Page 1",
command=lambda: controller.show_frame(PageOne))
button.pack()
button2 = tk.Button(self, text="Visit Page 2",
command=lambda: controller.show_frame(PageTwo))
button2.pack()
class PageOne(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label = tk.Label(self, text="Page One!!!", font=LARGE_FONT)
label.pack(pady=10,padx=10)
button1 = tk.Button(self, text="Back to Home",
command=lambda: controller.show_frame(StartPage))
button1.pack()
button2 = tk.Button(self, text="Page Two",
command=lambda: controller.show_frame(PageTwo))
button2.pack()
btns = MainButtonFrame(self,SeaofBTCapp)
btns.pack()
class PageTwo(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label = tk.Label(self, text="Page Two!!!", font=LARGE_FONT)
label.pack(pady=10,padx=10)
button1 = tk.Button(self, text="Back to Home",
command=lambda: controller.show_frame(StartPage))
button1.pack()
button2 = tk.Button(self, text="Page One",
command=lambda: controller.show_frame(PageOne))
button2.pack()
btns = MainButtonFrame(self,SeaofBTCapp)
btns.pack()
class MainButtonFrame(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
Pages = [StartPage,PageOne,PageTwo ]
for button in Pages:
NewButton = tk.Button(self, text=str(button),
command=lambda: controller.show_frame(button))
NewButton.pack()
app = SeaofBTCapp()
app.mainloop()
我得到的错误信息是:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1536, in __call__
return self.func(*args)
File "<ipython-input-13-dcc5fdbf1581>", line 103, in <lambda>
command=lambda: controller.show_frame(button))
TypeError: unbound method show_frame() must be called with SeaofBTCapp
instance as first argument (got classobj instance instead)
如果能在按钮命令中提示我做错了什么,我们将不胜感激。如果我能得到这个工作,我会用它作为一个框架来构建一个更大的 GUI。谢谢!
【问题讨论】:
-
您已经拥有
button1和button2来在不同的帧之间导航......为什么要添加这些btns = MainButtonFrame(self,SeaofBTCapp)?
标签: python python-2.7 user-interface tkinter