我有一些從互聯網上復制的自動完成組合框的代碼,我正在修改它,以便我可以通過像普通組合框這樣的關鍵字更改其屬性,如寬度、高度、系結等。我不確定如何呼叫屬性的函式,因為我需要 self. 在它后面啟動功能。這是我所擁有的片段:
from tkinter import *
from tkinter import ttk
class App(Tk):
def __init__(self):
Tk.__init__(self)
self.CBBox = AutoCompleteBox(self, height=3)
self.CBBox.pack()
class AutoCompleteBox(ttk.Combobox):
def __init__(self, parent, **kwargs):
ttk.Combobox.__init__(self, parent)
for key, value in kwargs.items():
key(value)
def height(self, height):
self.config(height=height)
def width(self, width):
self.config(width=width)
my_app = App()
my_app.mainloop()
uj5u.com熱心網友回復:
如果您詢問如何將 kwargs 傳遞給基類,只需在呼叫時傳遞它們__init__:
class AutoCompleteBox(ttk.Combobox):
def __init__(self, parent, **kwargs):
ttk.Combobox.__init__(self, parent, **kwargs)
要在基類上呼叫方法,請使用super。或者,像在__init__和 呼叫類中那樣做。super是首選。
例如,如果你想呼叫configure基類的方法,你可以這樣做:
def width(self, width):
super().config(width=width)
在這種情況下,沒有必要,因為self.config(...)將自動呼叫config基類上的方法,因為您沒有在類中覆寫該方法。
如果您定義自己的config方法來執行除默認行為之外的其他操作,則它可能如下所示:
def config(self, **kwargs):
print("config called:", kwargs)
super().config(**kwargs)
請注意,如果您洗掉最后一行,當您呼叫config它時將列印訊息,但它實際上不會配置小部件。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/323746.html
上一篇:Tkinter僅在創建結束時顯示
下一篇:方法上的Tkinter型別錯誤
