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
There are a number of issues with your code:
example
be visible in the method, you either have to declare it globally, or you have to do self.example
.get()
, you want to work with the IntVar
var
, not with the Checkbox itself.var
needs to be self.var
to be visible.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()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.