tkinter变量类未定义

时间:2018-11-29 16:52:18

标签: python tkinter

我正在尝试打印出tkinter条目中的内容,但是我一直遇到有关未定义变量类的错误。

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

我的控制台在这里:

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

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

您无法访问变量ageVar,因为该变量未在此函数的范围内定义。使其成为您的类的参数(通过使用self方法)。顺便说一下,您应该在类中添加一个构造函数。

将您的代码更改为:

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