我正在尝试将optionmenu和listbox结合起来指导字典中的选择。一切似乎都很好。但是,我得到了AttributeError: 'App' object has no attribute 'listbox'
。知道为什么这个错误?此外,是否可以使用旋转框代替列表框?
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python34\lib\tkinter\__init__.py", line 1487, in __call__
return self.func(*args)
File "C:/Users/Sam/Desktop/dict.py", line 40, in updateoptions
self.listbox.delete(0, 'end')
AttributeError: 'App' object has no attribute 'listbox'
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python34\lib\tkinter\__init__.py", line 1487, in __call__
return self.func(*args)
File "C:/Users/Sam/Desktop/dict.py", line 40, in updateoptions
self.listbox.delete(0, 'end')
AttributeError: 'App' object has no attribute 'listbox'
这是我的代码:
from tkinter import *
from tkinter import ttk
import tkinter.messagebox
class App:
def __init__(self):
self.master = Tk()
self.di = {'Asia': ['Japan', 'China', 'Malaysia', 'India', 'Korea',
'Vietnam', 'Laos', 'Thailand', 'Singapore',
'Indonesia', 'Taiwan'],
'Europe': ['Germany', 'France', 'Switzerland'],
'Africa': ['Nigeria', 'Kenya', 'Ethiopia', 'Ghana',
'Congo', 'Senegal', 'Guinea', 'Mali', 'Cameroun',
'Benin', 'Tanzania', 'South Africa', 'Zimbabwe']}
self.variable_a = StringVar()
self.frame_optionmenu = ttk.Frame(self.master)
self.frame_optionmenu.pack()
self.variable_a.trace('w', self.updateoptions)
options = sorted(self.di.keys())
self.optionmenu = ttk.OptionMenu(self.frame_optionmenu, self.variable_a, options[0], *options)
self.variable_a.set('Asia')
self.optionmenu.pack()
self.btn = ttk.Button(self.master, text="Submit", width=8, command=self.submit)
self.btn.pack()
self.frame_listbox = ttk.Frame(self.master)
self.frame_listbox.pack(side=RIGHT, fill=Y)
self.scrollbar = Scrollbar(self.frame_listbox )
self.scrollbar.pack(side=RIGHT, fill=Y)
self.listbox = Listbox(self.frame_listbox, selectmode=SINGLE, yscrollcommand=self.scrollbar.set)
self.scrollbar.config(command=self.listbox.yview)
self.listbox.pack()
#Populate listbox
for each in self.di[self.variable_a.get()]:
self.listbox.insert(END, each)
self.listbox.bind("<Double-Button-1>", self.OnDouble)
self.master.mainloop()
def updateoptions(self, *args):
countries = self.di[self.variable_a.get()]
self.listbox.delete(0, 'end')
for each in self.di[self.variable_a.get()]:
self.listbox.insert(END, each)
self.listbox.pack()
def submit(self, *args):
var = self.variable_a.get()
if messagebox.askokcancel("Selection", "Confirm selection: " + var):
print(var)
def OnDouble(self, event):
widget = event.widget
selection = widget.curselection()
value = widget.get(selection[0])
print(value)
App()
使用Python 3.4.1
答案 0 :(得分:1)
您的updateoptions
方法引用了self.listbox
,但可能会在定义self.listbox
之前调用它。
移动
self.variable_a.trace('w', self.updateoptions)
到下面定义self.listbox
的地方
self.listbox = Listbox(self.frame_listbox, selectmode=SINGLE, yscrollcommand=self.scrollbar.set)
self.variable_a.trace('w', self.updateoptions)