隐藏所有这些网格,以便我可以创建另一个“页面”

时间:2013-07-10 21:01:34

标签: python tkinter

from tkinter import *

rGui = Tk()
rGui.title("Recipe's")
rGui.geometry("400x300")
rGui.resizable(0,0)

rNameLabel = Label(rGui, text="What is your Recipe called?").grid(row=1, column=1)
rEnt = Entry(rGui)
rEnt.grid(row=1, column=2)


def RecipeName():
    f = open(rEnt.get()+'.txt','a')
    f.write("Recipe name: "+str(rEnt.get())+"\n")
    f.close()
rConButton = Button(rGui, text="Confirm", command=RecipeName).grid(row=1, column=3)

您好,这里的代码打开了一个带按钮的GUI。现在,一旦用户输入了他们的食谱名称,我希望它能够清除屏幕,这样我就可以添加更多按钮。现在我不确定如何让grid_forget工作,所以如果有人可以编辑代码,那么它会忘记它,这样下次我就可以看一下它了。

1 个答案:

答案 0 :(得分:1)

这是如何使用grid几何管理器在程序中创建页面的一个示例:

import tkinter

class Application(tkinter.Frame):

    @classmethod
    def main(cls):
        tkinter.NoDefaultRoot()
        root = tkinter.Tk()
        root.title('Recipes')
        root.geometry('400x300')
        root.resizable(False, False)
        app = cls(root)
        app.grid()
        root.mainloop()

    def __init__(self, master):
        super().__init__(master)
        self.create_first_screen()
        self.first_screen.grid_remove()
        self.create_second_screen()
        self.second_screen.grid_remove()
        self.first_screen.grid()

    def create_first_screen(self):
        self.first_screen = s1 = tkinter.Frame(self)
        self.first_screen.grid(row=0, column=0)
        # Create widgets.
        s1.name_label = tkinter.Label(s1, text='What is your recipe called?')
        s1.name_entry = tkinter.Entry(s1)
        s1.con_button = tkinter.Button(s1, text='Confirm',
                                       command=self.name_recipe)
        # Grid each widget.
        s1.name_label.grid(row=0, column=0)
        s1.name_entry.grid(row=0, column=1)
        s1.con_button.grid(row=0, column=2)

    def create_second_screen(self):
        self.second_screen = s2 = tkinter.Frame(self)
        self.second_screen.grid(row=0, column=0)
        # Create widgets.
        s2.name_label = tkinter.Label(s2, text='What is your name?')
        s2.name_entry = tkinter.Entry(s2)
        s2.con_button = tkinter.Button(s2, text='Confirm',
                                       command=self.name_yourself)
        # Grid each widget.
        s2.name_label.grid(row=0, column=0)
        s2.name_entry.grid(row=0, column=1)
        s2.con_button.grid(row=0, column=2)

    def name_recipe(self):
        name = self.first_screen.name_entry.get()
        with open(name + '.txt', 'w') as file:
            print('Recipe name:', name, file=file)
        self.first_screen.grid_remove()
        self.second_screen.grid()

    def name_yourself(self):
        name = self.second_screen.name_entry.get()
        with open(name + '.txt', 'w') as file:
            print('Your name:', name, file=file)
        self.second_screen.grid_remove()
        self.first_screen.grid()

if __name__ == '__main__':
    Application.main()