首页 > 解决方案 > Python:辅助窗口没有完全破坏

问题描述

我正在做一个 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()

文件弹出.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()

以上是我的代码,我从主屏幕调用了类,它在 tkinter 中showPopup()使用创建新的弹出窗口。Toplevel()但即使我破坏了弹出窗口,它也应该返回主窗口并打印“弹出窗口被破坏”,但事实并非如此。

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

标签: pythontkinter

解决方案


经过一番折腾,我找到了解决方案。

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

看来主要错误来自您showPopup()popup()函数中声明类的对象。

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

为了解决上述问题,我不得不以另一种方式导入弹出窗口。由于您只使用 showPopup 类,只需执行from popup import showPopup. 现在摆脱popup.showPopup()如果你已经把它放下了,因为那是行不通的。

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

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

完整代码:

主脚本.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()

弹出.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()


推荐阅读