如果我做对了,我想您的意思是说拥有某种 基类 ,该 基类 具有一些配置,这些配置具有一组共同的框架,例如,您想要具有10个 300x400
几何形状且共同具有 棕色 背景的框架后来又有了另一组 框架,它们具有不同的配置
,可以以有组织的方式进行访问。然后我会说您有一种有趣的方式,但是无论如何我还是希望使用列表或字典。
这里有一些实现这一目标的方法。
方法1
通过这种方法,我创建了一个函数,该函数返回一个字典,其中包含所有创建并包含在其中的框架,如格式(
{..., 'F20': tkinter.frame,...})import tkinter as tkdef get_base_frames(num, master, cnf={}, **kw): """ Create list of frames with common configuration options. Args: num (int): Number of frames to be created. master (tk.Misc): Takes tkinter widget or window as a parent for the frames. cnf (dict): configuration options for all the frames. kw: configuration options for all the frames. Return: Dictionary of frames ({..., 'F20': tkinter.frame, ...}). """ return {f'F{n+1}': tk.frame(master, cnf=cnf, **kw) for n in range(num)}if __name__ == "__main__": root = tk.Tk() frame_holder = get_base_frames(10, root, width=50, height=50, bg='brown') # frames can be accessed through their names like so. print(frame_holder.get('F1'))方法2
在这里,我使用了类和对象。我在哪堂课
frames上讲,您可以随便命名。我还添加了一些重要的方法,例如
cget()和
configure(),通过这些方法,一旦获得一个选项的值并分别为所有框架配置选项。
还有一些更有用的方法,例如
bind(),
bind_all()如果需要,只需根据需要修改此类。
import tkinter as tkclass frames(object): def __init__(self, master=None, cnf={}, **kw): super().__init__() num = cnf.pop('num', kw.pop('num', 0)) for n in range(num): self.__setattr__(f'F{n+1}', tk.frame(master, cnf=cnf, **kw)) def configure(self, cnf={}, **kw): """Configure resources of a widget. The values for resources are specified as keyword arguments. To get an overview about the allowed keyword arguments call the method keys. """ for frame in self.__dict__: frame = self.__getattribute__(frame) if isinstance(frame, tk.frame): if not cnf and not kw: return frame.configure() frame.configure(cnf=cnf, **kw) config = configure def cget(self, key): """Return the resource value for a KEY given as string.""" for frame in self.__dict__: frame = self.__getattribute__(frame) if isinstance(frame, tk.frame): return frame.cget(key) __getitem__ = cgetif __name__ == "__main__": root = tk.Tk() frame_holder = frames(root, num=10, width=10, bd=2, relief='sunken', bg='yellow') # frames can be accessed through their naems like so. print(frame_holder.F4) print(frame_holder['bg']) frame_holder.config(bg='blue') print(frame_holder['bg'])方法3
如果要 在一个类中包含不同配置的框架,则 所有这些框架具有某种共同的方法或某种共同的属性。
import tkinter as tkclass baseframe(tk.frame): def __init__(self, master=None, cnf={}, **kw): super().__init__(master=master, cnf={}, **kw) def common_function(self): """This function will be common in every frame created through this class.""" # Do something...class frameHolder(object): def __init__(self, master=None, cnf={}, **kw): kw = tk._cnfmerge((cnf, kw)) num = kw.pop('num', len(kw)) for n in range(num): name = f'F{n+1}' cnf = kw.get(name) self.__setattr__(name, baseframe(master, cnf))if __name__ == "__main__": root = tk.Tk() holder = frameHolder(root, F1=dict(width=30, height=40, bg='black'), F2=dict(width=50, height=10, bg='green'), F3=dict(width=300, height=350, bg='blue'), F4=dict(width=100, height=100, bg='yellow'), ) print(holder.F1) print(holder.__dict__)方法4
这是OP试图实现的方法。
import tkinter as tkclass baseClass(tk.frame): def __init__(self, master, cnf={}, **kw): kw = tk._cnfmerge((cnf, kw)) cnf = [(i, kw.pop(i, None)) for i in ('pack', 'grid', 'place') if i in kw] tk.frame.__init__(self, master, **kw) self.master = master if cnf: self.__getattribute__(cnf[-1][0])(cnf=cnf[-1][1])class Container(tk.frame): """Container class which can contain tkinter widgets. Geometry (pack, grid, place) configuration of widgets can also be passed as an argument. For Example:- >>> Container(root, widget=tk.Button, B5=dict(width=30, height=40, bg='black',fg='white', pack=(), text='Button1'), B6=dict(width=50, height=10, bg='green', text='Button2',place=dict(relx=0.5, rely=1, anchor='s'))) """ baseClass = baseClass def __init__(self, master=None, cnf={}, **kw): kw = tk._cnfmerge((cnf, kw)) wid = kw.pop('widget', tk.frame) for name, cnf in kw.items(): geo = [(i, cnf.pop(i, None)) for i in ('pack', 'grid', 'place') if i in cnf] setattr(Container, name, wid(master, cnf)) if geo: manager, cnf2 = geo[-1] widget = getattr(Container, name) getattr(widget, manager)(cnf=cnf2)if __name__ == "__main__": root = tk.Tk() Container(root, widget=Container.baseClass, F1=dict(width=30, height=40, bg='black', relief='sunken',pack=dict(ipadx=10, ipady=10, fill='both'), bd=5), F2=dict(width=50, height=10, bg='green',pack=dict(ipadx=10, ipady=10, fill='both')), ) Container(root, widget=tk.Button, B5=dict(width=30, height=40, bg='black',fg='white', pack={}, text='Button1'), B6=dict(width=50, height=10, bg='green', text='Button2',place=dict(relx=0.5, rely=1, anchor='s')), ) print(Container.__dict__) root.mainloop()许多事情可以完成,也可以根据自己的需求进行修改,这些只是我认为可以很好地实现一组框架的自动运行并保持形状一致的一些方法。
有多种方法可以做到这一点,或者有比这些更好,更有效的方法,您可以随时提出建议并分享新知识。



