[英]How do I create different Tkinter frames across multiple files?
I am creating a GUI on Tkinter that needs to open or close windows when buttons are pressed, and I would prefer if each window was in its own file. 我正在Tkinter上创建一个GUI,该GUI在按下按钮时需要打开或关闭窗口,我希望每个窗口都在其自己的文件中。 I tried creating a very simple example of this with the three files below. 我尝试使用下面的三个文件创建一个非常简单的示例。 The first window is supposed to have a button that, when pressed, closes the current window and opens the next one. 第一个窗口应该有一个按钮,当按下该按钮时,它会关闭当前窗口并打开下一个窗口。 I'm currently running into a problem where the window is created but the button is not. 我当前遇到创建窗口但按钮未创建的问题。 How do I fix this? 我该如何解决?
Main.py 主程序
from MyTkWindow import *
myWindow = MyTkWindow()
myWindow.start()
MyTkWindow.py MyTkWindow.py
import tkinter as tk
from NextFrame import *
class MyTkWindow(tk.Frame):
def __init__(self, parent=None):
tk.Frame.__init__(self)
nextWin = NextWindow()
NextScreen = tk.Button(self, text="Next", command=lambda:[self.destroy(), nextWin.start()])
NextScreen.pack()
def start(self):
self.mainloop()
NextFrame.py NextFrame.py
import tkinter as tk
class NextWindow(tk.Frame):
def __init__(self, parent=None):
tk.Frame.__init__(self)
Leave = tk.Button(self, text="Quit", command=lambda: self.destroy())
Leave.pack()
def start(self):
self.mainloop()
I got this to work with the indicated changes. 我将其与指示的更改一起使用。 The primary problem was due to not calling the pack()
method of the windows/frames being created. 主要问题是由于未调用要创建的Windows /框架的pack()
方法。
main.py
: main.py
:
from MyTkWindow import *
myWindow = MyTkWindow()
myWindow.pack() # ADDED
myWindow.start()
MyTkWindow.py
: MyTkWindow.py
:
import tkinter as tk
from NextFrame import *
class MyTkWindow(tk.Frame):
def __init__(self, parent=None):
tk.Frame.__init__(self, parent) # ADDED parent argument.
nextWin = NextWindow()
NextScreen = tk.Button(self, text="Next",
command=lambda: [self.destroy(),
nextWin.pack(), # ADDED
nextWin.start()])
NextScreen.pack()
def start(self):
self.mainloop()
NextFrame.py
: NextFrame.py
:
import tkinter as tk
class NextWindow(tk.Frame):
def __init__(self, parent=None):
tk.Frame.__init__(self, parent) # ADDED parent argument.
Leave = tk.Button(self, text="Quit",
command=lambda: self.destroy())
Leave.pack()
def start(self):
self.mainloop()
Suggestion: Read and start following the PEP 8 - Style Guide for Python Code because it will make your code more understanable and maintainable. 建议:阅读并开始遵循PEP 8-Python代码样式指南,因为它会使您的代码更易于理解和维护。 Specifically, the Naming Conventions section especially with respect to class, variable, and module file names. 具体来说,“ 命名约定”部分特别是关于类,变量和模块文件名的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.