首页 文章

Python / Tkinter退出堆叠帧的按钮

提问于
浏览
0

我正计划使用Tkinter为高级项目在Python中创建一个相当复杂的GUI . 我遇到了this链接,提供了一种很好的结构化方法,可以通过堆叠来处理帧之间的切换 .

我想制作一个简单的退出按钮,在按下时退出程序,因为我打算制作的GUI不会有围绕它的窗口框架,以最小化,最大化或退出 . 如果我添加如下函数:

def quit_program(self):

    self.destroy()

我将该函数放在show_frame函数下面,然后在另一个类中调用它,如下所示:

button3 = tk.Button(self, text="Quit",
                        command=lambda: controller.quit_program)

它不起作用 . 这是为什么?我将如何使用此框架结构制作一个退出按钮?

2 回答

  • 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 中的函数_1180679中添加了一个按钮 . 它可以在这里找到,名称为 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
    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)
    

相关问题