导入一个Python文件,当主窗口按钮点击时,创建一个窗口

2024-10-03 13:16:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我在我的程序中创建了2个窗口,我使用了两个类,因为代码很复杂,所以我把它分成两个不同的python文件。导入第二个窗口文件后,如何确保它打开而不会出现此图片中显示的错误enter image description here

单击“新建窗口”按钮后,原始结果应如下所示: enter image description here

主窗口编码:

from tkinter import *
import classGUIProgram
class Window(Tk):
    def __init__(self, parent):
        Tk.__init__(self, parent)
        self.parent = parent
        self.initialize()

    def initialize(self):
        self.geometry("600x400+30+30")
        self.wButton = Button(self, text='newWindow', command =     self.OnButtonClick)
        self.wButton.pack()

    def OnButtonClick(classGUIProgram):
        classGUIProgram.top = Toplevel()
        master = Tk()
        b = classGUIProgram.HappyButton(master)
        master.mainloop()
if __name__ == "__main__":
    window = Window(None)

    window.title("title")

    window.mainloop()

第二个窗口的编码:

^{pr2}$

Tags: 文件importselfmaster编码initdefwindow
1条回答
网友
1楼 · 发布于 2024-10-03 13:16:41

您正在创建额外的Tk窗口。下面是一个使用Toplevel小部件和另一个文件的示例。在

主窗口.py

import tkinter as tk
import secondWindow as sW

class MainWindow(tk.Tk):
    def __init__(self):
        super().__init__()
        self.title("Main Window")
        self.geometry("600x400+30+30")

        tk.Button(self, text = "New Window", command = self.new_window).pack()
        tk.Button(self, text = "Close Window", command = self.close).pack()

        self._second_window = None

    def new_window(self):
        # This prevents multiple clicks opening multiple windows
        if self._second_window is not None:
            return

        self._second_window = sW.SubWindow(self)

    def close(self):
        # Destory the 2nd window and reset the value to None
        if self._second_window is not None:
            self._second_window.destroy()
            self._second_window = None


if __name__ == '__main__':
    window = MainWindow()
    window.mainloop()

第二窗口.py

^{pr2}$

使用另一个文件时,请确保没有您不希望运行的任何全局代码。您的类不必继承Tk和{},这只是一个例子。但是您需要确保您只有一个Tk的实例,否则您将得到您遇到的行为

相关问题 更多 >