如何在 Tkinter 中在兩個框架之間切換?
在大多數情況下,你需要多個螢幕,以允許使用者在你程式的不同片段之間切換。實現此目的的一種方法是建立位於主視窗內的單獨框架。
A-Frame 元件用於在應用程式中對過多元件進行分組。我們可以在兩個不同的框架中新增單獨的元件。使用者可以透過單擊按鈕從一個框架切換到另一個框架。
示例
在這個應用程式中,我們將建立一個單獨的框架問候框架和訂單框架。每個框架由兩個不同的物件組成。一個按鈕將用於在兩個不同的框架物件之間進行切換。
# Import the required libraries from tkinter import * from tkinter import font # Create an instance of tkinter frame or window win = Tk() # Set the size of the window win.geometry("700x350") # Create two frames in the window greet = Frame(win) order = Frame(win) # Define a function for switching the frames def change_to_greet(): greet.pack(fill='both', expand=1) order.pack_forget() def change_to_order(): order.pack(fill='both', expand=1) greet.pack_forget() # Create fonts for making difference in the frame font1 = font.Font(family='Georgia', size='22', weight='bold') font2 = font.Font(family='Aerial', size='12') # Add a heading logo in the frames label1 = Label(greet, text="Hey There! Welcome to TutorialsPoint.", foreground="green3", font=font1) label1.pack(pady=20) label2 = Label(order, text="Find all the interesting Tutorials.", foreground="blue", font=font2) label2.pack(pady=20) # Add a button to switch between two frames btn1 = Button(win, text="Switch to Greet", font=font2, command=change_to_order) btn1.pack(pady=20) btn2 = Button(win, text="Switch to Order", font=font2, command=change_to_greet) btn2.pack(pady=20) win.mainloop()
輸出
執行上述程式碼將顯示一個包含兩個不同框架的視窗。
可以使用其中定義的一個按鈕在這些框架之間進行切換。
廣告