Drew Wood
Drew Wood

Reputation: 91

tkinter variable classes not defined

I am trying to print out the contents in a tkinter entry, however i keep running into errors about the variable classes not being defined.

import tkinter as tk
from tkinter import *
from tkinter import ttk

class queryCreator( Frame ):

    master = tk.Tk()

    tk.Label(master, text="Age").grid(row=0)
    tk.Label(master, text="Birth Place").grid(row=1)

    ageVar = tk.IntVar()
    birthPlaceVar = tk.StringVar()

    e1 = tk.Entry(master, textvariable=ageVar)    
    e2 = tk.Entry(master)

    e1.grid(row=0, column=1)
    e2.grid(row=1, column=1)

    def createQuery():

        print(ageVar.get())

    createQueryButton = Button(master, text="Create Query", command=createQuery).grid(row=10)

    master.mainloop( )

def main(): 
    queryCreator().mainloop()
if __name__ == '__main__':
    main()

My console is here:

drews-MacBook-Pro-2:Desktop drewwood$ python3 DBGUI.py 
Exception in Tkinter callback
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/tkinter/__init__.py", line 1699, in __call__
return self.func(*args)
  File "DBGUI.py", line 23, in createQuery
print(ageVar.get())
NameError: name 'ageVar' is not defined

Any help would be really appreciated.

Upvotes: 1

Views: 872

Answers (1)

David Duran
David Duran

Reputation: 1826

You cannot access the variable ageVar since it is not defined in the scope of this function. Make it a parameter of your class (by using self method). By the way, you should add a constructor in your class.

Change your code into something like:

import tkinter as tk
from tkinter import *
from tkinter import ttk

class queryCreator( Frame ):

    def __init__(self):
        master = tk.Tk()

        tk.Label(master, text="Age").grid(row=0)
        tk.Label(master, text="Birth Place").grid(row=1)

        self.ageVar = tk.IntVar()
        birthPlaceVar = tk.StringVar()

        e1 = tk.Entry(master, textvariable=self.ageVar)    
        e2 = tk.Entry(master)

        e1.grid(row=0, column=1)
        e2.grid(row=1, column=1)

        createQueryButton = Button(master, text="Create Query", command=self.createQuery).grid(row=10)

        master.mainloop( )

    def createQuery(self):
        print(self.ageVar.get())

def main(): 
    queryCreator()

if __name__ == '__main__':
    main()

Upvotes: 1

Related Questions