这是如何使用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()