我正计划使用Tkinter为高级项目在Python中创建一个相当复杂的GUI。我遇到了this链接,提供了一种结构化的方式来处理帧之间的切换。
我想制作一个简单的退出按钮,在按下时退出程序,因为我打算制作的GUI不会有围绕它的窗口框架,以最小化,最大化或退出。如果我添加如下函数:
def quit_program(self):
self.destroy()
我将该函数放在show_frame函数下面,然后在另一个类中调用它,如下所示:
button3 = tk.Button(self, text="Quit",
command=lambda: controller.quit_program)
它不起作用。这是为什么?我将如何使用此框架结构制作一个退出按钮?
答案 0 :(得分:1)
我已经接受了你的代码,我可以看到它的一些错误。通过一些操作,我设法使它工作。这是结果:
import Tkinter as tk
root = tk.Tk()
button3 = tk.Button(text="Quit", command=lambda: quit_program())
def quit_program():
root.destroy()
button3.pack()
root.mainloop()
祝你好运!
约旦。
-----编辑-----
抱歉,我没有完全阅读你的问题。希望这有助于你的努力。
我将Brian的代码放入程序中,我就像你说的那样添加了destroy函数。然后,我在函数StartPage
中的类__init__
中添加了一个按钮。它可以在这里找到,名称为button3
。
class StartPage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
label = tk.Label(self, text="This is the start page",
font=controller.title_font)
label.pack(side="top", fill="x", pady=10)
button1 = tk.Button(self, text="Go to Page One",
command=lambda:
controller.show_frame("PageOne"))
button2 = tk.Button(self, text="Go to Page Two",
command=lambda:
controller.show_frame("PageTwo"))
button3 = tk.Button(self, text="Quit",
command=lambda:
controller.quit_program())
button1.pack()
button2.pack()
button3.pack()
我的代码最终完美运行,当您按下按钮时,它退出程序。我想你会发现,当你调用quit_program
函数时,你会把它称为:controller.quitprogram
,你应该在它后面的括号中添加它,因为它是一个函数,像:controller.quit_program()
。我还没有看到你实际在你的代码中添加了什么,但在你的问题中,你没有在你的电话中加入括号。
希望这有帮助!
约旦。
答案 1 :(得分:1)
button3 = tk.Button(self, text="Quit",
command=lambda: controller.quit_program)
没有button3
来调用任何内容,因为它在()
内缺少调用lambda
语法。替换为:
button3 = tk.Button(self, text="Quit",
command=lambda: controller.quit_program())
或更好用:
button3 = tk.Button(self, text="Quit",
command=controller.quit_program)
此外,如果要进行退出功能,可以使用quit
方法,因为它会销毁所有GUI,而不是像destroy
那样附加的对象:
button3 = tk.Button(self, text="Quit",
command=controller.quit)