我对类继承没有太多经验。我知道你可以通过*args和**kwargs将任何变量传递给类实例,这有助于容纳子类。
在下面的例子中,我想在实例化一个类时传递标题,主题和大小,这将为我做:self.title('App')
和self.set_theme('radiance')
。现在我只是替换属性,即self.title = 'App'
和self.set_theme = 'radiance'
不做我想要的…
class App(ThemedTk):
def __init__(self, **kwargs):
super().__init__()
self.__dict__.update(kwargs)
dic = {
'title': 'App',
'set_theme': 'radiance',
}
app = App(**dic)
app.mainloop()
我相信你正在寻找这样的东西
from ttkthemes import ThemedTk
class App(ThemedTk):
def __init__(self, **kwargs):
title=kwargs.pop('title','')
theme=kwargs.pop('set_theme',None)
super().__init__(**kwargs)
self.title(title)
if theme:
self.set_theme(theme)
dic = {
'title': 'App',
'set_theme': 'radiance',
}
app = App(**dic)
app.mainloop()
您可以在开始时将pop
(kwargs.pop(key, default)
)取出未进入ThemedTk
的__init__
函数的kwargs
,然后将它们传递到各自的方法中。
基于@AST的回答:
from ttkthemes import ThemedTk
class App(ThemedTk):
# The default value for `title` is "Tk" and
# the default value for `theme` is `None`
def __init__(self, title="Tk", theme=None, **kwargs):
super().__init__(**kwargs)
self.title(title)
# If the theme is None just skip it
if theme is not None:
self.set_theme(theme)
dic = {
'title': 'App',
'set_theme': 'radiance',
}
app = App(**dic)
app.mainloop()