我计划使用Tkinter在Python中制作一个相当复杂的GUI,用于高级项目。 我碰到了这个链接,该链接提供了一种很好的结构化方法,可以通过堆叠框架来处理框架之间的切换。
我想制作一个简单的退出按钮,当按下该按钮时退出程序,因为我计划制作的GUI周围没有最小化,最大化或退出窗口框。 如果我添加这样的功能:
def quit_program(self):
self.destroy()
然后将该函数放在show_frame函数下面,然后在另一个类中对其进行调用,如下所示:
button3 = tk.Button(self, text="Quit",
command=lambda: controller.quit_program)
没用 这是为什么? 我将如何使用这种框架结构制作退出按钮?
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)
我已经接受了您的代码,并且看到了一些错误。通过一些操作,我设法使其工作。结果如下:
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函数。然后,在函数__init__中的类StartPage中添加了一个按钮。可以在这里找到,名称为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() 。我没有看到您在代码中实际输入的内容,但是在您的问题中,您未在通话中包含括号。
希望这可以帮助!
约旦。
请记住,我已经使用python 2.7来做到这一点。
感谢您的答复,但是它不是我想要的。 我试图在链接中发布的代码中添加退出按钮。 我完全理解您的答案,但是我希望找到一个答案,如果将它添加到我在问题中链接的Brain Oakley发表的答案中,为什么它不起作用。 抱歉,如果我的问题不够清楚,请首先在堆栈溢出上发表!
抱歉 参见编辑版本。
您可以处理lambda:将command=lambda: controller.quit_program())替换为command=controller.quit_program)