Prodigal
Prodigal

Reputation: 13

Python - Tkinter - setting IntVar's in a list

I've written an app that takes some data from the user, queries the API of a website, and returns and processes the data given by the API. I'm trying to allow the user greater control of what happens next by creating checkboxes for each item retrieved.

Because the number of items retrieved will vary on each use, I'm putting the checkboxes and the IntVars for if they're checked or not into lists. However, when I try to set the IntVars to 1 (so they all start out checked) I get a TypeError telling me it wants the IntVar instance as the first arg, but that doesn't make any sense to me as I'm trying to call a method for the IntVar in the first place.

This is a much simplified version of my code that generates an identical error:

import Tkinter as tk

class Application(tk.Frame):
    def __init__(self, master=None):
        tk.Frame.__init__(self, master)
        self.grid()

        self.test_names = ["Box 1", "Box 2", "Box 3", "Box 4"]
        self.boxes = []
        self.box_vars = []
        self.box_num = 0

        btn_test1 = tk.Button(self, text="Test 1", width = 11, command = self.test1)
        btn_test1.grid()

    def test1(self):
        for name in self.test_names:
            self.box_vars.append(tk.IntVar)
            self.boxes.append(tk.Checkbutton(self, text = name, variable = self.box_vars[self.box_num]))
            self.box_vars[self.box_num].set(1)
            self.boxes[self.box_num].grid(sticky = tk.W)
            self.box_num += 1

root = tk.Tk()
app = Application(master=root)
app.mainloop()

And the error message when pushing the button:

TypeError: unbound method set() must be called with IntVar instance as first
argument (got int instance instead)

What am I doing wrong?

Upvotes: 1

Views: 3310

Answers (2)

Fame Castle
Fame Castle

Reputation: 33

Yes you forgot the brackets. The result will be and not a tkinter intvar instance.

Upvotes: 0

Eric Levieil
Eric Levieil

Reputation: 3574

Classic problem. You add the type IntVar instead of adding an object of type IntVar. Add parentheses like this:

self.box_vars.append(tk.IntVar())

Upvotes: 4

Related Questions