简体   繁体   English

Tkinter 名称错误

[英]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我正在尝试制作一个简单的程序,它可以 select 程序并启动它们,但是当我 select 列表中的一个 porgram 时,它给出了一个名称错误

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 NameError:名称“示例”未定义

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我取得的唯一进展是从def example后面删除(self) ,然后出现以下错误

TypeError: example() takes 0 positional arguments but 1 was given TypeError: example() 采用 0 位置 arguments 但给出了 1

any help would be very appreciated任何帮助将不胜感激

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 .正如评论中所指出的,为了让example在方法中可见,您要么必须全局声明它,要么必须执行self.example
  • in order to do get() , you want to work with the IntVar var , not with the Checkbox itself.为了执行get() ,您需要使用IntVar var ,而不是 Checkbox 本身。
  • then again, var needs to be self.var to be visible.再说一遍, var必须是self.var才能可见。
  • finally, var needs to be an instance of IntVar , so you need bracket: var = IntVar()最后, var需要是IntVar的一个实例,所以你需要括号: 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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM