【发布时间】:2021-10-28 06:23:43
【问题描述】:
我发现了一些困扰我的事情。
VSCode 的一个重要特性是我在编写采用 **kw 的 tkinter 类时得到的类型提示。这是一个例子:
现在我正在尝试从 Tk.Canvas() 类创建一个子类,幸运的是,vscode 已经完成了写下来的艰苦工作:
class MyCanvas(Tk.Canvas):
def __init__(self, master: Misc | None, cnf: dict[str, Any] | None, *, background: _Color, bd: _ScreenUnits, bg: _Color, border: _ScreenUnits, borderwidth: _ScreenUnits, closeenough: float, confine: bool, cursor: _Cursor, height: _ScreenUnits, highlightbackground: _Color, highlightcolor: _Color, highlightthickness: _ScreenUnits, insertbackground: _Color, insertborderwidth: _ScreenUnits, insertofftime: int, insertontime: int, insertwidth: _ScreenUnits, name: str, offset: Any, relief: _Relief, scrollregion: Tuple[_ScreenUnits, _ScreenUnits, _ScreenUnits, _ScreenUnits] | Tuple[()], selectbackground: _Color, selectborderwidth: _ScreenUnits, selectforeground: _Color, state: Literal["normal", "disabled"], takefocus: _TakeFocusValue, width: _ScreenUnits, xscrollcommand: _XYScrollCommand, xscrollincrement: _ScreenUnits, yscrollcommand: _XYScrollCommand, yscrollincrement: _ScreenUnits) -> None:
super().__init__(master=master, cnf=cnf, background=background, bd=bd, bg=bg, border=border, borderwidth=borderwidth, closeenough=closeenough, confine=confine, cursor=cursor, height=height, highlightbackground=highlightbackground, highlightcolor=highlightcolor, highlightthickness=highlightthickness, insertbackground=insertbackground, insertborderwidth=insertborderwidth, insertofftime=insertofftime, insertontime=insertontime, insertwidth=insertwidth, name=name, offset=offset, relief=relief, scrollregion=scrollregion, selectbackground=selectbackground, selectborderwidth=selectborderwidth, selectforeground=selectforeground, state=state, takefocus=takefocus, width=width, xscrollcommand=xscrollcommand, xscrollincrement=xscrollincrement, yscrollcommand=yscrollcommand, yscrollincrement=yscrollincrement)
但是这个定义是完全错误的:它将属性视为 vars 而不是**kw,并且引用了未定义的类,例如_Color 和_ScreenUnits。于是我去Tk.Canvas.__init__()定义看看是怎么回事,我发现了这个:
def __init__(self, master=None, cnf={}, **kw):
"""Construct a canvas widget with the parent MASTER.
Valid resource names: background, bd, bg, borderwidth, closeenough,
confine, cursor, height, highlightbackground, highlightcolor,
highlightthickness, insertbackground, insertborderwidth,
insertofftime, insertontime, insertwidth, offset, relief,
scrollregion, selectbackground, selectborderwidth, selectforeground,
state, takefocus, width, xscrollcommand, xscrollincrement,
yscrollcommand, yscrollincrement."""
Widget.__init__(self, master, 'canvas', cnf, kw)
所以在这里我很困惑,因为在类定义中没有单一的类型提示。那么我得到的所有这些“类型提示”是从哪里来的呢?有没有办法让它出现在我的孩子班级的**kw?
【问题讨论】:
标签: python tkinter visual-studio-code type-hinting python-typing