如何清除Tkinter上的页面

时间:2013-08-08 19:08:20

标签: python tkinter

如何清除Tkinter上的窗口?这是我的代码:

import sys
from tkinter import *

mGui = Tk ()
mGui.geometry("600x600+545+170")
mGui.title("MyMathDictionary")
mLabel1 = Label (text = "Welcome to MyMathDictionary. Press Next to continue.",fg = "blue",bg = "white").place (x= 150,y = 200)
mbutton = Button (text = "Next").place(x = 275,y = 230)
mGui.mbutton = (mbutton.forget())

1 个答案:

答案 0 :(得分:1)

您遇到的问题是由两件事引起的:您placedefine小部件name = somewidget()的同一行中的小部件,而您实际上并未删除小部件。第mGui.mbutton = (mbutton.forget())行并没有真正做任何事情。您应该在小部件定义行中使用command={function name},这样您就可以在单击按钮时调用函数。

.forget()应该有效,但你使用它错了。你应该使用这样的东西:

import sys
import tkinter
from tkinter import *


def next_screen():
    mLabel1.place_forget()
    mbutton.place_forget()

mGui = tkinter.Tk()
mGui.geometry("600x600+545+170")
mGui.title("MyMathDictionary")

mLabel1 = tkinter.Label(text="Welcome to MyMathDictionary. Press Next to continue.",
                        fg="blue", bg="white")
mLabel1.place(x=150, y=200)

mbutton = tkinter.Button(text="Next", command=next_screen)
mbutton.place(x=275, y=230)

.pack().place()置于与定义按钮或标签相同的行中,将导致窗口小部件以某种方式变为nonetype。我自己并不完全理解这一点,但将widget.place()放在一个单独的行上有帮助,你可以自己测试一下。

更好的是类似于将小部件名称列表作为输入的函数,并将删除每个小部件:

mbutton = tkinter.Button(text="Next", command=forget_page1)
mbutton.place(x=275, y=230)

def next_screen(names):
    for widget in names:
        widget.place_forget()   

def forget_page1():
    widgets = [mLabel1, mbutton]
    next_screen(widgets)
    # Code for the creation of page2 widgets

# You could probably make a function for every page, but I'm sure
# someone could come up with a better answer, instead of repeat
# making functions.
def forget_page2():
    widgets = [page2label, page2button, image]
    next_screen(widgets)
    # Code for the creation of the widgets on page3?