Python:辅助窗口未完全销毁

时间:2020-07-09 05:42:33

标签: python tkinter

我正在做一个Tkinter项目,以了解python和tkinter。 我陷入了这样一种情况,即我从主窗口调用了辅助弹出窗口,并且在弹出窗口被销毁后,它不再返回主屏幕。

文件mainScr.py

import tkinter as tk
import popup

root = tk.Tk()
root.overrideredirect(True)
width = root.winfo_screenwidth()
height = root.winfo_screenheight()
root.geometry('%dx%d+%d+%d' % (width*0.8, height*0.8, width*0.1, height*0.1))

def popup():
    showPopup()
    print("popup destroyed")

show_btn = tk.Button(root, command= popup) 
show_btn.pack()

root.mainloop()

文件popup.py

import tkinter as tk

class showPopup():
    def __init__(self):
        self.popup = tk.Toplevel()
        self.popup.title("Details")
        w = 400     # popup window width
        h = 250     # popup window height
        sw = self.popup.winfo_screenwidth()
        sh = self.popup.winfo_screenheight()
        x = (sw - w)/2
        y = (sh - h)/2
        self.popup.geometry('%dx%d+%d+%d' % (w, h, x, y))
        self.show()
        self.popup.mainloop()

    def save(self):        
        self.popup.destroy()

    def show(self):
        save_btn = tk.Button(self.popup, text="Save", command= self.save)
        save_btn.pack()

以上是我的代码,我从主屏幕调用了showPopup()类,该类在tkinter中使用Toplevel()创建了新的弹出窗口。 但是,即使我销毁了弹出窗口,它也应返回主窗口并打印“ popup destroy”,但不是。

弹出窗口正在关闭,但未执行print语句。当我关闭主窗口时,控制台然后执行打印语句

1 个答案:

答案 0 :(得分:2)

经过一番混乱,我找到了解决方法。

(这是在您对我先前的注释进行了先前的更改之后,其中包含我后来为解决此问题而更改的代码)。

似乎主要的错误来自于您在showPopup()函数中声明了popup()类的对象。

我要做的第一个修复是showPopup来自另一个文件。为了解决这个问题,我写了popup.showPopup(),但这是不对的,因为代码认为它是一个函数。

要解决上述问题,我不得不以其他方式导入弹出窗口。由于您仅使用showPopup类,因此只需执行from popup import showPopup。现在,如果您已经将popup.showPopup()放下了,因为它行不通了,那就摆脱它。

现在,您只需要在类上调用save()。为此,我将showPopup()类分配给了一个名为new的变量,然后在其下调用了new.save()

我还删除了popup.mainloop(),因为TopLevel()不需要它

完整代码:

mainScr.py:

import tkinter as tk
from popup import showPopup

root = tk.Tk()
root.overrideredirect(True)
width = root.winfo_screenwidth()
height = root.winfo_screenheight()
root.geometry('%dx%d+%d+%d' % (width * 0.8, height * 0.8, width * 0.1, height * 0.1))


def popup():
    new = showPopup()
    new.save()
    print("popup destroyed")


show_btn = tk.Button(root, command=popup)
show_btn.pack()

root.mainloop()

popup.py:

import tkinter as tk


class showPopup():
    def __init__(self):
        self.popup = tk.Toplevel()
        self.popup.title("Details")
        w = 400  # popup window width
        h = 250  # popup window height
        sw = self.popup.winfo_screenwidth()
        sh = self.popup.winfo_screenheight()
        x = (sw - w) / 2
        y = (sh - h) / 2
        self.popup.geometry('%dx%d+%d+%d' % (w, h, x, y))

    def save(self):
        self.popup.destroy()

    def show(self):
        save_btn = tk.Button(self.popup, text="Save", command=self.save)
        save_btn.pack()