yuk*_*say 2 python architecture initialization definition
我收到以下代码的相关警告:
from tkinter import *
from tkinter import ttk
class Autocomplete(Frame, object):
def __init__(self, *args, **kwargs):
super(Autocomplete, self).__init__(*args, **kwargs)
self.list = []
def build(self, width, height, entries):
# I get the warning for the following 8 lines:
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()
return self
root = Frame(Tk())
autocomplete = Autocomplete(root).build(74, 10, entries)
root.pack()
autocomplete.pack()
mainloop()
Run Code Online (Sandbox Code Playgroud)
我应该如何解决这个问题?我试图将所有内容都移动到 init 但后来我在创建 Autocompelete 对象的行中传递参数时遇到了一些错误。因此,请向我提供我必须做出的所有更改。不仅仅是像你必须移动它们那样。我可以通过添加 8 行将 None 分配给所有变量来修复警告,但我认为这是一个愚蠢的解决方案。那么正确的做法是什么?
请务必记住,并非所有警告都需要修复。警告只是警告。他们应该指出代码的特定部分,因为它是问题的“常见”来源。但有时你需要/想要这样做。
我可以通过添加 8 个定义行来修复警告,将 None 分配给所有变量
这只是“沉默”警告,在我看来这与忽略警告一样好。
那么正确的做法是什么?
正确的方法是使用__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()
Run Code Online (Sandbox Code Playgroud)