Tkinter:未定义全局名称

时间:2015-04-30 11:27:49

标签: python tkinter

我正在尝试将项目添加到列表框中,但每次尝试时,都会说全局名称“title_input”未定义。我不明白为什么这不起作用,因为我用这个完全相同的结构做的最后一个没有给我那个错误。我是新手,我读到的关于全局名称错误的其他教程和问题对我来说没有意义。谢谢你的帮助!

from Tkinter import *

class Application(Frame):

def __init__(self, master):
    Frame.__init__(self, master)
    self.grid()
    self.create_widgets()
    self.list = Listbox(self, selectmode=BROWSE)
    self.list.grid(row = 1, column = 4, rowspan = 10, columnspan = 3, sticky = W, padx = 5, pady = 5)

def create_widgets(self):
    #setlist box - may not stay text box?
    self.setlist = Text(self, height = 14, width = 25)
    self.setlist.grid(row = 1, column = 0, rowspan = 10, columnspan = 3, sticky = W, padx = 5, pady = 5)

    self.setlistLabel = Label(self, text = "SetList")
    self.setlistLabel.grid(row = 0, column = 1, sticky = W, padx = 5, pady = 5)

    #Library label
    self.libraryLabel = Label(self, text = "Library")
    self.libraryLabel.grid(row = 0, column = 5, sticky = W, padx = 5, pady y = 5)

    #Library button/input

    self.add_title = Button(self, text = "Add Title", command = self.add_item)
    self.add_title.grid(row = 16, column = 5, sticky = W, padx = 5, pady = 5)

    self.title_input = Entry(self)
    self.title_input.grid(row = 16, column = 4, sticky = W, padx = 5, pady = 5)

def add_item(self):
    list.insert(END, title_input.get())

def get_list(event):
    index = list.curselection()[0]
    seltext = list.get(index)
    setlist.insert(0, seltext)

root = Tk()
root.title("SetList Creator")
root.geometry("500x500")

app = Application (root)

root.mainloop()

1 个答案:

答案 0 :(得分:0)

title_input在您的实例命名空间中定义,但未在您的全局命名空间中定义。当您在类方法title_input中引用非限定add_item时,Python会在全局命名空间中查找title_input。当它没有找到它时,它会给你错误。添加self限定符self.title_input以表示您希望在实例名称空间中引用title_input,将解决该错误。