Ashish101
Ashish101

Reputation: 135

Text to appear as checkbox is clicked in Python Tkinter

I am coding a GUI in Python 2.7 and I am making checkboxes. I want to know how to make a text appear right beside the checkbox when it is checked and unchecked. For eg. When I check the checkbox the text beside the checkbox should be 'enable' and when I uncheck the checkbox the text should be 'disable'.

Upvotes: 1

Views: 1260

Answers (2)

acw1668
acw1668

Reputation: 46669

You can assign same StringVar to textvariable and variable options of Checkbutton and set onvalue='enable' and offvalue='disable'. Then whenever the state of the checkbutton changes, the text changes:

import tkinter as tk

root = tk.Tk()

var = tk.StringVar(value='disable')
tk.Checkbutton(root, textvariable=var, variable=var, onvalue='enable', offvalue='disable').pack()

root.mainloop()

Upvotes: 4

Bryan Oakley
Bryan Oakley

Reputation: 385940

There's nothing particularly difficult about this. Checkbuttons can call a command when toggled. You can change the text inside the command using the configure method of the widget.

Here's a simple example:

import tkinter as tk

def toggle(widget):
    variable = widget.cget("variable")
    value = int(widget.getvar(variable))
    label = "enable" if value else "disable"
    widget.configure(text=label)

root = tk.Tk()

for i in range(10):
    cb = tk.Checkbutton(root, text="disable")
    cb.configure(command=lambda widget=cb: toggle(widget))
    cb.pack(side="top")

root.mainloop()

Upvotes: 2

Related Questions