如何实现Tkinter主菜单按钮点击后跳转至新GUI菜单并关闭原菜单
Absolutely, using classes is the right approach here—it keeps your code organized, reusable, and avoids messy global variables. Let's refactor your code into two window classes: one for the main menu, and another for the "view table" menu. When the button is clicked, we'll destroy the main menu window and launch the new one.
Here's the complete implementation:
import tkinter as tk class MainMenu(tk.Tk): def __init__(self): super().__init__() # Set window dimensions self.HEIGHT = 700 self.WIDTH = 800 self.geometry(f"{self.WIDTH}x{self.HEIGHT}") # Create main canvas and frame canvas = tk.Canvas(self, height=self.HEIGHT, width=self.WIDTH) canvas.pack() frame = tk.Frame(self, bg='#8BDFF4') frame.place(relx=0.1, rely=0.1, relwidth=0.8, relheight=0.5) # Create button that triggers window switch button1 = tk.Button( frame, text="view table", bg='#8BF4AB', fg='black', activebackground='#62AF7A', command=self.open_table_menu # Bind click to our method ) button1.place(relx=0, rely=0, relwidth=0.25, relheight=0.25) def open_table_menu(self): # Close the main menu window self.destroy() # Launch the table menu window table_menu = TableMenu() table_menu.mainloop() class TableMenu(tk.Tk): def __init__(self): super().__init__() self.HEIGHT = 700 self.WIDTH = 800 self.geometry(f"{self.WIDTH}x{self.HEIGHT}") canvas = tk.Canvas(self, height=self.HEIGHT, width=self.WIDTH) canvas.pack() frame = tk.Frame(self, bg='#8BDFF4') frame.place(relx=0.1, rely=0.1, relwidth=0.8, relheight=0.5) # Add the "inflows" button for this menu button1 = tk.Button( frame, text="inflows", bg='#8BF4AB', fg='black', activebackground='#62AF7A' ) button1.place(relx=0, rely=0.35, relwidth=0.25, relheight=0.25) # Start the main menu when the script runs if __name__ == "__main__": app = MainMenu() app.mainloop()
Key Details Explained:
- Class Structure: Each window is its own class inheriting from
tk.Tk, which makes it easy to add more menus later (like an "Edit" menu or "Settings" menu) without rewriting core logic. - Window Switch Logic: The
open_table_menumethod handles two critical steps:self.destroy()closes the main menu window completely.- We create a new instance of
TableMenuand start its main loop to show the new window.
- Cleaner Code: By encapsulating each window's UI elements inside its class, you avoid cluttering your global namespace and make it easier to debug or modify individual menus.
If you want to add a way to go back to the main menu from the table menu, you'd just add a similar button and method in the TableMenu class that destroys itself and launches MainMenu again.
内容的提问来源于stack exchange,提问作者samuel west
相关产品推荐
相关产品推荐

