How to make a simple checkbox in customtkinter python
Fri Jul 28 2023 11:36:31 GMT+0000 (Coordinated Universal Time)
Saved by
@pythonHub
#python
#python-hub
#ctk
#oop
# Importing the necessary modules from customtkinter library
from customtkinter import *
# This function will be called when the checkbox is toggled
def checkbox_event():
# Create a new CTkLabel widget and display the current value of the checkbox
label = CTkLabel(app, text=f"checkbox toggled, current value: {check_var.get()}")
label.pack()
# Create a CTk application instance
app = CTk()
# Create a StringVar to hold the value of the checkbox (initially empty)
check_var = StringVar()
# Create a CTkCheckBox widget with text "Switch"
# When the checkbox is toggled, the checkbox_event function will be called
# The checkbox's variable is check_var, and its values are "on" (checked) and "off" (unchecked)
checkbox = CTkCheckBox(app, text="Switch", command=checkbox_event,
variable=check_var, onvalue="on", offvalue="off")
# Pack the checkbox widget, adding padding around it
checkbox.pack(padx=10, pady=10)
# Start the main event loop of the application
app.mainloop()
"""
# ------------------IN OOP------------------
# Create a custom application class "App" that inherits from CTk (Custom Tkinter)
class App(CTk):
# Constructor of the class
def __init__(self):
# Call the constructor of the parent class (CTk) using super()
super().__init__()
# Create a StringVar to hold the value of the checkbox (initially empty)
self.check_var = StringVar()
# Create a CTkCheckBox widget with text "Switch"
# When the checkbox is toggled, the self.checkbox_event method will be called
# The checkbox's variable is self.check_var, and its values are "on" (checked) and "off" (unchecked)
self.checkbox = CTkCheckBox(self, text="Switch", command=self.checkbox_event,
variable=self.check_var, onvalue="on", offvalue="off")
# Pack the checkbox widget, adding padding around it
self.checkbox.pack(padx=10, pady=10)
# Method to handle the checkbox toggle event
def checkbox_event(self):
# Create a new CTkLabel widget and display the current value of the checkbox
label = CTkLabel(self, text=f"checkbox toggled, current value: {self.check_var.get()}")
label.pack()
# Create an instance of the custom application class "App"
app = App()
app.mainloop()
"""
content_copyCOPY
Comments