Tkinter Checkbutton and event callback function
Asked Answered
U

3

7

Here is a little code example I found on the Effbot website which is close to what I want to do in one of my programs:

from Tkinter import *

fen =Tk()

class test_Tk_class:
    def __init__(self):
        self.var = IntVar()
        c = Checkbutton(
            fen, text="Enable Tab",
            variable=self.var,
            command=self.cb)
        c.pack()

    def cb(self,event):
        print "variable is", self.var.get()

    a = test_Tk_class()
    fen.mainloop()

However this code is not working. The callback function cb does not work because it takes 2 arguments and none are given. How do you specify the event argument?

Unregenerate answered 3/10, 2013 at 15:52 Comment(0)
W
11

This code does not need event at all in this case. I got it working by just removing it altogether:

def cb(self):
    print "variable is", self.var.get()

The only time you would structure your code that way is if you are binding functions to key presses or mouse clicks. For checking/unchecking a checkbutton however, it is not needed.

I don't know what the person who coded this on Effbot was trying to do, but I don't think he did it right. Maybe he made a typo or had something else in mind.

Walloping answered 3/10, 2013 at 16:1 Comment(1)
even better is to use event=None so that the callbacks will work for button and bindingsCovenantor
C
2

You could use none-event version of your function. This method allows you to use it for either Checkbutton command or event callback. You may find the amended version below:

def cb(self,event=None):
    print "variable is", self.var.get()
Chaldron answered 14/12, 2018 at 12:23 Comment(0)
S
0

I want to add the following for completeness, which allows any number of input arguments (and could be useful for trace_add:

def cb(self, *_):
    print "variable is", self.var.get()
Sloane answered 9/7 at 23:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.