Tkinter navigation with frames
你好,
我真的被这个python代码困扰了。也许你能帮我?
我想用按钮导航页面。我有三个不同的相框。然后我按下一个按钮,一个框架在其他框架之上,但不要隐藏其他框架。
如果我对你的问题不清楚,试试我的代码,你就会明白我的意思。
此代码来自但很少修改。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 | import tkinter as tk from tkinter import ttk from tkinter import StringVar LARGE_FONT= ("Verdana", 12) class Application(tk.Tk): def __init__(self, *args, **kwargs): tk.Tk.__init__(self, *args, **kwargs) tk.Tk.wm_title(self,"Title") container = tk.Frame(self, width=768, height=1000) container.pack(side="top", fill='both' , expand = 1) container.grid_rowconfigure(0, weight=1) container.grid_columnconfigure(0, weight=1) self.frames = {} for F in (StartPage, PageOne, PageTwo): frame = F(container, self) self.frames[F] = frame #frame.pack() frame.grid(row=0, column=0) self.show_frame(StartPage) def show_frame(self, cont): frame = self.frames[cont] frame.tkraise() class StartPage(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self,parent) label = ttk.Label(self, text="Start Page", font=LARGE_FONT) label.pack(pady=10,padx=10) button = ttk.Button(self, text="Visit Page 1", command=lambda: controller.show_frame(PageOne)) button.pack() button2 = ttk.Button(self, text="Visit Page 2", command=lambda: controller.show_frame(PageTwo)) button2.pack() class PageOne(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) label = ttk.Label(self, text="Page One!!!", font=LARGE_FONT) label.pack(pady=0,padx=100) button1 = ttk.Button(self, text="Back to Home", command=lambda: controller.show_frame(StartPage)) button1.pack() button2 = ttk.Button(self, text="Page Two", command=lambda: controller.show_frame(PageTwo)) button2.pack() class PageTwo(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) label = ttk.Label(self, text="Page Two!!!", font=LARGE_FONT) label.pack(pady=0,padx=0) button1 = ttk.Button(self, text="Back to Home", command=lambda: controller.show_frame(StartPage)) button1.pack() button2 = ttk.Button(self, text="Page One", command=lambda: controller.show_frame(PageOne)) button2.pack() phone = StringVar() home = ttk.Radiobutton(self, text='Home', variable=phone, value='home') office = ttk.Radiobutton(self, text='Office', variable=phone, value='office') cell = ttk.Radiobutton(self, text='Mobile', variable=phone, value='cell') home.pack() office.pack() cell.pack() app = Application() app.mainloop() |
非常感谢:)
你需要告诉所有的帧使用所有可用的空间,以便它们覆盖下面的任何帧。你可以用粘乎乎的论点来做到这一点:
1 | frame.grid(row=0, column=0, sticky='nsew') |
这就意味着框架要贴在北部、南部、东部和西部;换句话说,在两个方向上填满所有的空间。