【问题标题】:How do I create different Tkinter frames across multiple files?如何跨多个文件创建不同的 Tkinter 帧?
【发布时间】:2019-09-05 16:25:58
【问题描述】:

我正在 Tkinter 上创建一个 GUI,它需要在按下按钮时打开或关闭窗口,我希望每个窗口都在自己的文件中。我尝试使用以下三个文件创建一个非常简单的示例。第一个窗口应该有一个按钮,当按下它时,关闭当前窗口并打开下一个窗口。我目前遇到了创建窗口但没有创建按钮的问题。我该如何解决这个问题?

main.py

from MyTkWindow import *

myWindow = MyTkWindow()
myWindow.start()

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

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()

【问题讨论】:

  • 我不明白这段代码是如何创建一个窗口的:你当然没有在任何地方请求创建一个窗口。 (调用框架“窗口”不会使其成为一体!)您必须调用Tk() 来初始化它并创建初始窗口,您必须将其作为第一个参数实际传递给您的框架,以便它具有定义的父级,您必须在 Frame 上调用 .pack() 或其他几何管理方法才能真正使其在窗口中可见。

标签: python tkinter


【解决方案1】:

我得到了这个与指示的更改一起工作。主要问题是由于没有调用正在创建的窗口/框架的pack() 方法。

main.py

from MyTkWindow import *

myWindow = MyTkWindow()
myWindow.pack()  # ADDED

myWindow.start()

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

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()

建议:阅读并开始关注PEP 8 - Style Guide for Python Code,因为它会使您的代码更易于理解和维护。具体来说,Naming Conventions 部分尤其是关于类、变量和模块文件名的部分。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-25
    • 2020-12-15
    相关资源
    最近更新 更多