务必记住,并非所有警告都需要修复。警告只是警告。他们应该指出代码的特定部分,因为这是问题的“常见”来源。但有时你需要/想那样做。在I could fix the warning by adding 8 definition lines assigning None to all the variables
这只是“压制”警告,在我看来,这和忽视警告一样好。在So what is the right thing to do?
正确的方法是使用__init__。我做了一个快速测试,没有任何问题。在
然而,这只是一个例子,一个人如何能做到这一点。我没有检查Frame想要什么作为__init__的参数,因此它可能会导致冲突:from tkinter import *
from tkinter import ttk
class Autocomplete(Frame, object):
def __init__(self, *args, **kwargs):
width, height, entries = kwargs.pop('width'), kwargs.pop('height'), kwargs.pop('entries')
super(Autocomplete, self).__init__(*args, **kwargs)
self.list = []
self._entries = entries
self.listbox_height = height
self.entry_width = width
self.text = StringVar()
self.entry = ttk.Entry(self, textvariable=self.text, width=self.entry_width)
self.frame = Frame(self)
self.listbox = Listbox(self.frame, height=self.listbox_height, width=self.entry_width)
self.dropdown = Listbox(self.frame, height=self.listbox_height, width=self.entry_width, background="#cfeff9",
takefocus=0)
self.entry.pack()
self.frame.pack()
self.listbox.grid(column=0, row=0, sticky=N)
self.dropdown.grid(column=0, row=0, sticky=N)
self.dropdown.grid_forget()
root = Frame(Tk())
autocomplete = Autocomplete(root, width=74, height=10, entries=entries)
root.pack()
autocomplete.pack()
mainloop()