[파이썬] tkinter 체크박스(`Checkbutton`) 위젯

In this blog post, we will explore how to create checkboxes using the Tkinter library in Python. Checkboxes are a commonly used widget that allow users to select options from a predefined list.

Getting Started

To begin, make sure that you have Tkinter installed. Tkinter comes pre-installed with Python, so you should have it available without needing to install any additional packages.

Creating a Checkbutton

To create a Checkbutton widget in Tkinter, we can use the Checkbutton class. Here is a basic example of how to create a checkbox:

import tkinter as tk

def toggle_checkbox():
    if checkbox_var.get() == 1:
        print("Checkbox is checked!")
    else:
        print("Checkbox is not checked.")

root = tk.Tk()

checkbox_var = tk.IntVar()
checkbox = tk.Checkbutton(root, text="Check me", variable=checkbox_var, command=toggle_checkbox)
checkbox.pack()

root.mainloop()

In the code above, we first import the tkinter module and define a function toggle_checkbox that will be called when the checkbox state changes. Next, we create an instance of the Tk class to create the main window.

We create an IntVar object (checkbox_var) to store the state of the checkbox. This variable will be set to 1 if the checkbox is checked, and 0 if it is unchecked.

Then, we create an instance of the Checkbutton class, passing in the root window as the first argument. We provide the text argument to set the label of the checkbox, the variable argument to bind the checkbox state to the checkbox_var variable, and the command argument to specify the function to be called when the checkbox is clicked.

Finally, we call the pack method on the checkbox widget to display it in the window, and start the main event loop using the mainloop method of the Tk instance.

Handling Checkbox Events

In the example above, we specified the toggle_checkbox function as the command to be executed when the checkbox is clicked. This function checks the value of the checkbox_var variable to determine whether the checkbox is checked or unchecked, and prints the appropriate message.

You can modify the toggle_checkbox function to perform any action you want when the checkbox state changes.

Conclusion

In this blog post, we learned how to create checkboxes using the Checkbutton widget in Tkinter. Checkboxes are a simple yet powerful way to allow users to select options in a graphical user interface. Experiment with the code provided and see what else you can do with checkboxes in your Tkinter applications.