【发布时间】:2019-04-19 14:42:39
【问题描述】:
在我的程序中,我从我的根 tkinter 窗口创建一个窗口,并使用 .withdraw() 函数隐藏根。当我尝试通过调用根类再次显示根窗口时,它没有显示并且我的程序退出。这是我描述问题的代码的粗略轮廓:
class MainGUI:
def __init__(self, master):
self.master = master
#....Create and .grid() all GUI Widgets....
# Button for switching to other window
button = Button(text="CLICKME", command=lambda: self.other_window())
# Call and define show function at the end of __init__
self.show()
def show(self):
self.master.update()
self.master.deiconify()
# Create other window and withdraw self on button click
def other_window(self):
OtherGUI(self.master)
self.master.withdraw()
class OtherGUI:
def __init__(self, master):
# Function for returning to main window, calls MainGUI class
# to create window and withdraws self.
def main_window():
MainGUI(self.master)
self.master.withdraw()
master = self.master = Toplevel(master)
#....Create and .grid() all GUI Widgets....
# Button for switching back to main window
button = Button(text="CLICKME", command=lambda: self.main_window())
使用 MainGUI 中的打印功能,我可以看到在尝试切换回主窗口时,实际上调用了 show(),并且似乎进入了整个类。
这让我很困惑,因为我只是从其他论坛帖子中真正学会了如何做到这一点,并且使用 root.update() 和 .deiconify() 似乎是大多数人的解决方案,但我不知道为什么会这样不工作。
有人知道我在哪里出错了吗?
【问题讨论】:
-
我不确定您是否将
MainGui方法缩进错误,或者您是否真的忘记将它们放在__init__之外。但是在OtherGui中,main_window必须在 init 之外并且有 self 参数 -
我认为构建一个分别从
tk和toplevel继承的类会更容易。我也确实在这里看到了缩进问题。通常在大多数 tkinter 应用程序中都不需要使用update()。
标签: python user-interface tkinter window show