Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tkinter checkbox with command attached

I would like some help with something simple: A tkinter checkbox that does have a command attached <--this simple example is always mentioned but never shown in tutorials on the web.

I have:

from tkinter import *

def activateMotors(active):
    scale.config(state=active)


root = Tk()
root.wm_title('Servo Control')
motorsOn= IntVar()
motorsCheck=Checkbutton(root,text="Motors ON(checked)/OFF(unchecked)", variable=motorsOn, command=activateMotors)
motorsCheck.pack()
scale = Scale(root, from_=0, to=180, 
              orient=HORIZONTAL,label="Motor #",state=DISABLED)
scale.pack()
root.mainloop()

This does not work. Sure the window comes up but when I click on the checkbox I get "TypeError activateMotors() missing 1 required positional argument 'active' "

Can anybody correct this so that we can have one operational checkbox example with commands?

like image 779
KansaiRobot Avatar asked Feb 05 '23 18:02

KansaiRobot


1 Answers

The callback must not have arguments, we must use the get() function of IntVar

from tkinter import *

def activateMotors():
    if motorsOn.get() == 1:
        scale.config(state=ACTIVE)
    elif motorsOn.get() == 0:
        scale.config(state=DISABLED)


root = Tk()
root.wm_title('Servo Control')
motorsOn= IntVar()
motorsCheck=Checkbutton(root, 
    text="Motors ON(checked)/OFF(unchecked)", 
    variable=motorsOn, 
    command=activateMotors)
motorsCheck.pack()

scale = Scale(root, from_=0, to=180, 
              orient=HORIZONTAL,label="Motor #",state=DISABLED)
scale.pack()
root.mainloop()
like image 129
eyllanesc Avatar answered Feb 07 '23 09:02

eyllanesc