Python Tkinter复选框';名称未定义';

Python Tkinter复选框';名称未定义';,python,checkbox,tkinter,Python,Checkbox,Tkinter,我目前正在编写一个应用程序,它使用Tkinter为用户提供图形界面 该应用程序一直运行良好,最近我决定添加一些复选框,其想法是当用户选中其中一个复选框时,另一组文本将通过API发送 我有一些输入框,可以很好地工作,但是由于某些原因,每当我尝试检索该复选框的值时,就会出现以下错误: if check.get(): NameError: name 'check' is not defined 就我的一生而言,我不明白为什么会出现这个错误,这是我的其余代码,为了更清楚,我已经删除了输入框的

我目前正在编写一个应用程序,它使用Tkinter为用户提供图形界面

该应用程序一直运行良好,最近我决定添加一些复选框,其想法是当用户选中其中一个复选框时,另一组文本将通过API发送

我有一些输入框,可以很好地工作,但是由于某些原因,每当我尝试检索该复选框的值时,就会出现以下错误:

     if check.get():
NameError: name 'check' is not defined
就我的一生而言,我不明白为什么会出现这个错误,这是我的其余代码,为了更清楚,我已经删除了输入框的工作代码

from tkinter import *

class GUI:
    def __init__(self, master):
         check = IntVar()



         self.e = Checkbutton(root, text="check me", variable=check)
         self.e.grid(row=4, column=2)

         self.macro_button = Button(master, text="Test Button", command=self.test)
         self.macro_button.grid(row=11, column=1)



      def test(self):
           if check.get():
                print('its on')
           else:
                print('its off')



root = Tk()
root.resizable(width=False, height=False)
my_gui = GUI(root)
root.mainloop()
当我运行此代码并按下标记为“测试按钮”的按钮时,即错误出现在我的终端中

有人知道为什么我的复选框会出现这种情况,而不是我的输入框吗

编辑:

对我来说更奇怪的是,我在网上找到的这段代码是用来教你如何使用tkinter复选框的,它就像一个符咒,几乎和我的代码一样:

import tkinter as tk

root = tk.Tk()

var = tk.IntVar()
cb = tk.Checkbutton(root, text="the lights are on", variable=var)
cb.pack()

def showstate():
    if var.get():
        print ("the lights are on")
    else:
        print ("the lights are off")

button = tk.Button(root, text="show state", command=showstate)
button.pack()

root.mainloop()

您只需使用
self
check
作为一个实例变量


您在网上找到的示例是以“内联”方式编写的,这在您的GUI变得更大,并且您需要使用/传递许多方法和变量之前是很好的。非常感谢您的回复,它工作得非常完美,很明显我对所有这些都是新手哈哈!当我不必对输入框中输入的文本变量执行相同操作时,为什么我必须使用self将其作为实例变量@Luke.py什么是输入框?你是说入门小部件吗?我可以在你的代码中看到任何一个这解决了您的问题吗?是的,我是说入口小部件,我知道我遗漏了它们,但我只是问了一个一般的python问题。是的,我的问题已经解决了谢谢@luke.py
class GUI:
    def __init__(self, master):
        self.check = IntVar()



        self.e = Checkbutton(root, text="check me", variable=self.check)
        self.e.grid(row=4, column=2)

        self.macro_button = Button(master, text="Test Button", command=self.test)
        self.macro_button.grid(row=11, column=1)



    def test(self):
        if self.check.get():
            print('its on')
        else:
            print('its off')



root = Tk()
root.resizable(width=False, height=False)
my_gui = GUI(root)
root.mainloop()