繁体   English   中英

Tkinter 名称错误

[英]Tkinter NameError

我正在尝试制作一个简单的程序,它可以 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()

当我运行它时,它工作正常,但是在单击复选框时它会给出错误

NameError:名称“示例”未定义

我尝试使用不同的关键字进行搜索,但没有找到解决方案。 我取得的唯一进展是从def example后面删除(self) ,然后出现以下错误

TypeError: example() 采用 0 位置 arguments 但给出了 1

任何帮助将不胜感激

您的代码存在许多问题:

  • 正如评论中所指出的,为了让example在方法中可见,您要么必须全局声明它,要么必须执行self.example
  • 为了执行get() ,您需要使用IntVar var ,而不是 Checkbox 本身。
  • 再说一遍, var必须是self.var才能可见。
  • 最后, var需要是IntVar的一个实例,所以你需要括号: var = IntVar()

总而言之,应用这些更改后,它将是:

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