[파이썬] tkinter 메뉴바 생성

tkinter

tkinter is a popular library in Python for creating graphical user interfaces (GUI). It provides various widgets and functionalities to build interactive applications. In this blog post, we will focus on creating a menu bar using tkinter.

Setting up tkinter

Before we dive into creating a menu bar, we need to install and import the tkinter library. To install tkinter, run the following command:

pip install tk

Next, import the necessary modules from tkinter:

from tkinter import Tk, Menu

Creating a basic menu bar

To create a menu bar, we’ll follow these steps:

  1. Create an instance of the Tk class to create the main window.
    window = Tk()
    
  2. Create an instance of the Menu class and associate it with the main window’s menu bar.
    menu_bar = Menu(window)
    window.config(menu=menu_bar)
    
  3. Create individual menu items using the add_command method of the Menu class.
    file_menu = Menu(menu_bar)
    file_menu.add_command(label="New")
    file_menu.add_command(label="Open")
    file_menu.add_command(label="Save")
    
  4. Add the individual menus or submenus to the main menu bar using the add_cascade method.
    menu_bar.add_cascade(label="File", menu=file_menu)
    
  5. Finally, enter the tkinter event loop to display the GUI.
    window.mainloop()
    

Example Code

Here’s the complete code to create a basic menu bar with “File” menu:

from tkinter import Tk, Menu

window = Tk()
menu_bar = Menu(window)
window.config(menu=menu_bar)

file_menu = Menu(menu_bar)
file_menu.add_command(label="New")
file_menu.add_command(label="Open")
file_menu.add_command(label="Save")

menu_bar.add_cascade(label="File", menu=file_menu)

window.mainloop()

Run the above code and you should see a GUI window with a “File” menu that drops down with options “New”, “Open”, “Save”.

Conclusion

In this blog post, we learned how to create a basic menu bar using tkinter in Python. As you delve further into tkinter, you can explore additional functionalities such as adding command bindings to menu items and creating submenus. Tkinter provides a wide range of possibilities for building intuitive and user-friendly graphical interfaces. Happy coding!