【问题标题】:Destroy everything inside a window outside of function Tkinter销毁函数 Tkinter 之外的窗口内的所有内容
【发布时间】:2014-03-06 10:35:41
【问题描述】:

在下面的代码中,我想在按下 GameButton 按钮时销毁窗口根目录内的所有内容,但是我希望发生其他事情,因此唯一的方法是让按钮运行一个函数。当我在主类之外执行 self.destroy 时,什么都没有被删除,有什么办法解决这个问题吗?

from PIL import Image, ImageTk
from Tkinter import Tk, Label, BOTH,W, N, E, S, Entry, Text, INSERT, Toplevel
from ttk import Frame, Style, Button, Label
import Tkinter
import Callingwordlist
difficulty = ""

class MainMenuUI(Frame):

    def __init__(self, parent):
        Frame.__init__(self, parent)   

        self.parent = parent

        self.initUI()

    def initUI(self):

        self.parent.title("Type!")
        self.pack(fill=BOTH, expand=1)

        style = Style()
        style.configure("TFrame", background="black")        

        Logo = Image.open("Type!.png")
        TypeLogo = ImageTk.PhotoImage(Logo)
        label1 = Label(self, image=TypeLogo)
        label1.image = TypeLogo
        label1.place(x=342,y=80)
        label1.pack()

        self.pack(fill=BOTH, expand=1)

        GameButton = Button(self, text="Main Game", command=lambda: main2(self.parent,self))
        GameButton.pack()
        GameButton.place(x=344,y=200,height = 80,width = 176)

        TutorialButton = Button(self,text="Tutorial Level")
        TutorialButton.pack()
        TutorialButton.place(x=344, y=300 ,height = 80,width = 176)

        quitbutton = Button(self, text= "Quit",command=self.parent.destroy)
        quitbutton.place(x=344, y=400,height = 80,width = 176)

def main2(root,self):
    self.destroy
    app = MainGameUI(root)
    root.mainloop()

class MainGameUI(root):
    ....

def main():

    root = Tk()
    root.geometry("860x640+300+300")
    app = MainMenuUI(root) 
    root.mainloop()

if __name__ == '__main__':
    main()

【问题讨论】:

    标签: python function tkinter window destroy


    【解决方案1】:

    你实际上并没有破坏你的函数中的任何东西。看这段代码:

    def main2(root,self):
        self.destroy
        app = MainGameUI(root)
        root.mainloop()
    

    请注意函数中的第一行,您试图销毁所有内容。您的代码是 self.destroy - 请注意缺少括号。你实际上并没有调用这个函数,你只是在引用它。添加括号来调用它:self.destroy()

    您还有另一个问题,您正在调用一个函数,该函数会破坏调用该函数的小部件。然而,这个函数进入了一个无限循环(mainloop()),所以按钮命令永远不会返回。我不完全确定这里会发生什么,您可能会遇到某种错误。底线是,从按钮命令调用mainloop 不是一个好主意。

    由于您正在构建应用程序以使应用程序是一个框架(而不是根窗口),因此您无需重新启动事件循环。当您销毁 MainMenuUI 小部件时,事件循环将继续运行。没有必要重新启动它。

    【讨论】:

    • 感谢您的建议,现在一切正常,删除 root.mainloop 减少了我的代码
    猜你喜欢
    • 1970-01-01
    • 2020-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-28
    • 1970-01-01
    相关资源
    最近更新 更多