1
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 工作,所以如果有人可以编辑代码,让它忘记它,这样我下次可以看看它,我会很感激的。

4

1 回答 1

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()
于 2013-07-11T20:42:32.447 回答