我对类继承没有太多的经验。我知道你可以通过*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()发布于 2021-03-12 05:43:49
我相信你正在寻找这样的东西
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,然后稍后将它们传递到各自的方法中。
发布于 2021-03-12 06:29:42
基于@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()https://stackoverflow.com/questions/66590386
复制相似问题