Tkinter NameError

I am trying to make a simple program that can select programs and start them, but when I select a porgram from the list it gives a name error

from tkinter import *

class Window(Frame):
    def __init__(self, master=None):
        Frame.__init__(self,master)
        self.pack(fill=BOTH, expand=1)

        var=IntVar

        example=Checkbutton(self, text="example", variable=var, onvalue=1, offvalue=0, command=self.example)
        example.place(x=0,y=0)
        
    def example(self):
        if (example.get() == 1):
            print("1")
        elif (example.get() == 0):
            print("0")

root=Tk()
app=Window(root)
root.geometry("220x120")
root.resizable(width=False, height=False)
root.mainloop()

When I run this, it works fine but upon clicking the checkbox it gives the error

NameError: name ‘example’ is not defined

i’ve tried searching with different keywords but haven’t found a solution. The only progress i made was to remove the (self) from behind def example, which then gave the following error

TypeError: example() takes 0 positional arguments but 1 was given

any help would be very appreciated

Answer

There are a number of issues with your code:

  • as pointed out in the comments, in order to have example be visible in the method, you either have to declare it globally, or you have to do self.example.
  • in order to do get(), you want to work with the IntVar var, not with the Checkbox itself.
  • then again, var needs to be self.var to be visible.
  • finally, var needs to be an instance of IntVar, so you need bracket: var = IntVar()

All in all, with those changes applied, it would be:

from tkinter import *

class Window(Frame):
    def __init__(self, master=None):
        Frame.__init__(self,master)
        self.pack(fill=BOTH, expand=1)

        self.var=IntVar()

        example=Checkbutton(self, text="example", variable=self.var, onvalue=1, offvalue=0, command=self.example)
        example.place(x=0,y=0)
        
    def example(self):
        if (self.var.get() == 1):
            print("1")
        elif (self.var.get() == 0):
            print("0")

root=Tk()
app=Window(root)
root.geometry("220x120")
root.resizable(width=False, height=False)
root.mainloop()

Leave a Reply

Your email address will not be published. Required fields are marked *