NameError:全局名称'END'未定义
我找到了一段关于滚动条的代码,运行得很好。
from tkinter import *
master = Tk()
scrollbar = Scrollbar(master)
scrollbar.pack(side=RIGHT, fill=Y)
listbox = Listbox(master, yscrollcommand=scrollbar.set)
for i in range(10000):
listbox.insert(END, str(i))
listbox.pack(side=LEFT, fill=BOTH)
scrollbar.config(command=listbox.yview)
mainloop()
我试着把它用在我的代码里,像这样:
import tkinter as tk
class interface(tk.Frame):
def __init__(self,den):
self.tklist()
#in my code, tklist is not called here. I called it here to minimize the code
#there are stuff in here also
def tklist(self):
scrollbar = tk.Scrollbar(den)
self.lst1 = tk.Listbox(den, selectmode="SINGLE", width="100", yscrollcommand=scrollbar.set)
for i in range(1000):
self.lst1.insert(END, str(i))
self.lst1.pack(side=LEFT, fill=BOTH)
scrollbar.config(command=lst1.yview)
den = tk.Tk()
den.title("Search")
inter = interface(den)
den.mainloop()
但是当我运行上面的代码时,在插入的那一行出现了错误。
NameError: global name 'END' is not defined
顺便说一下,我试着找一些文档,发现effbot的一个链接是我找到的最接近的资料,但我还是不明白哪里出了问题。
3 个回答
0
第一段代码能正常运行是因为你使用了 * 从 tkinter 中导入所有内容,但在第二段代码中,你是把 tkinter 作为 tk 导入的。所以你需要使用 tk.END。
def tklist(self):
scrollbar = tk.Scrollbar(den)
self.lst1 = tk.Listbox(den, selectmode="SINGLE", width="100", yscrollcommand=scrollbar.set)
for i in range(1000):
self.lst1.insert(tk.END, str(i))
self.lst1.pack(side=LEFT, fill=BOTH)
scrollbar.config(command=lst1.yview)
0
使用“end”而不是END
from tkinter import *
self.lst1.insert("end", str(i))
21
END
、LEFT
和 BOTH
都在 tkinter
这个命名空间里。所以在使用它们的时候,需要在前面加上 tk.
来标识:
for i in range(1000):
self.lst1.insert(tk.END, str(i))
self.lst1.pack(side=tk.LEFT, fill=tk.BOTH)
scrollbar.config(command=lst1.yview)
或者,如果你想的话,也可以直接把它们导入进来:
from tkinter import BOTH, END, LEFT