mercredi 28 septembre 2016

Tkinter checkbox 'Name not defined'

I am currently writing an application that uses Tkinter to provide a graphical interface for the user.

The app has been working very well and recently I decided to add some checkboxes, the idea being that when the user checks one of the boxes, another set of text is sent through an API.

I have input boxes that I am able to get to work perfectly, however for some reason whenever I try and retrieve the value of the checkbox, I get the following error:

     if check.get():
NameError: name 'check' is not defined

For the life of me I can't figure out why this error is popping up, here is the rest of my code, to make it clearer I have removed the working code for the input boxes.

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()

When I run this code, and press the button labeled 'test button', that is when the error appears in my terminal.

Anyone have any idea why this is happening for my checkboxes, and not for my inputboxes?

EDIT:

what's even odder for me is that this code that I found online made to teach you how to use a tkinter checkbox works like a charm, and its almost identical to mine:

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()




Aucun commentaire:

Enregistrer un commentaire