在没有按钮的情况下在 Tkinter 中切换帧

问题描述

我正在使用以下代码创建一个 Tkinter 窗口并切换它显示的帧。

import tkinter

class GUI(tkinter.Tk):
    def __init__(self):
        tkinter.Tk.__init__(self)
        self._frame = None
        self.switch(Frame1)

    def switch(self,frame_class):
        new_frame = frame_class(self)
        if self._frame is not None:
            self._frame.destroy()
        self._frame = new_frame
        self._frame.pack()


class Frame1(tkinter.Frame):
    def __init__(self,parent):
        tkinter.Frame.__init__(self,parent)
        tkinter.Label(self,text="Frame1").pack()

        parent.switch(Frame2) # not working
        tkinter.Button(self,text="switch",command=lambda: parent.switch(Frame2)).pack() # working


class Frame2(tkinter.Frame):
    def __init__(self,text="Frame2").pack()


if __name__ == '__main__':
    gui = GUI()
    gui.mainloop()

请注意,开关功能是在没有按钮的情况下执行的,但只能在点击时起作用。

解决方法

这是正在发生的事情:

  1. GUI 开始切换到第 1 帧
  2. 帧 1 已创建并切换到帧 2
  3. GUI 完成切换到第 1 帧

因此,应用程序在第 1 帧结束

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...