使用类在另一个类中设置参数 - Python

时间:2017-07-07 13:59:37

标签: python tkinter

我正在开发一个Tkinter GUI,我想在其单独的类中添加窗口大小调整和定位控件。 我的结构是这样的:

class MainApp(tk.Tk):

    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        container = tk.Frame(self)
        container.pack(side="top", fill="both", expand=True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)
        self.winsize= WinSize(container, 700, 500, 650, 450, True, True)

我希望WinSize设置主应用程序的几何形状以及句柄 WinSize类中的minsizeresizeable

class WinSize:

    def __init__(self, container, width, height, minx, miny, sizeablex, sizeabley):
        self.container = container
        self.width = width
        self.height = height
        self.minx = minx
        self.miny = miny
        self.sizeablex = sizeablex
        self.sizeabley = sizeabley
        self.ws = self.container.winfo_screenwidth()
        self.hs = self.container.winfo_screenheight()
        self.xpos = (self.ws / 2) - (self.width / 2)
        self.ypos = (self.hs / 2) - (self.height / 2)

我一直在广泛搜索,并没有找到关于如何在WinSize类中为特定实例和/或框架实现这些实现的解决方案/指导。 我想使用相同的类来设置弹出消息/框架的大小和其他属性,以显示其他信息。 主要的GUI类来自@Bryan Oakley着名的例子:https://stackoverflow.com/a/7557028/7703610

如何在Tk中调用geometryminsizeresizeable,而无需在WinSize类中再次继承Tk,然后将其应用于该特定实例?

1 个答案:

答案 0 :(得分:1)

有两种解决方案。您可以将窗口传递给WinSize()而不是容器,或者您可以使用winfo_toplevel方法获取特定窗口小部件的窗口。

第一个解决方案如下:

class MainApp(tk.Tk):

    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        ...
        self.winsize= WinSize(self, 700, 500, 650, 450, True, True)

class WinSize:

    def __init__(self, window, width, height, minx, miny, sizeablex, sizeabley):
        self.window = window
        ...
        self.window.geometry("%d%d+%d+%d" % (width, height, minx, miny))
        ...

第二个解决方案不需要更改主应用程序。只需将以下内容添加到WinSize

即可
class WinSize:
    def __init__(...):
        ...
        window = self.container.winfo_toplevel()
        self.window.geometry("%d%d+%d+%d" % (width, height, minx, miny))
相关问题