繁体   English   中英

如何在python tkinter中使用从一个类到另一个类的函数

[英]How to use functions from one class to another in python tkinter

如何在AddPart类中使用MainPage类中的AddPart 我在Mainpage类中有一些函数,并且想在另一个AddPart类中使用MainPage类中的所有函数。

class MainPage(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent) #initialise parent class --> TSS()


    def main_heading(self, heading):
        main_label = tk.Label(self, text = heading, font = LARGE_FONT, fg = 'white', bg = 'RoyalBlue1', width = 1000, height = 4)
        main_label.pack(side = 'top')

    def sub_heading(self, title):
        sub_label = tk.Label(self, text = title, font = MED_FONT, fg = 'RoyalBlue2')
        sub_label.pack(side = 'top', padx = 20, pady = 20)

    def paragraph(self, para):
        paragraph_label = tk.Label(self, text = para, font = SMALL_FONT, fg = 'gray26')
        paragraph_label.pack(side = 'top', padx = 20, pady = 20)

    def top_tool(self):
        toolbar = tk.Frame(self, bg = 'RoyalBlue2')
        AddBtn = tk.Button(toolbar, text = 'ADD', width = 10, bg = 'RoyalBlue2', fg = 'white', borderwidth=0)
        AddBtn.pack(side = 'left', padx = 0, pady = 0)
        RemBtn = tk.Button(toolbar, text = 'REMOVE', width = 10, bg = 'RoyalBlue2', fg = 'white', borderwidth=0)
        RemBtn.pack(side = 'left', padx = 0, pady = 0)
        RevBtn = tk.Button(toolbar, text = 'REVIEW', width = 10, bg = 'RoyalBlue2', fg = 'white', borderwidth=0)
        RevBtn.pack(side = 'left', padx = 0, pady = 0)
        AssignBtn = tk.Button(toolbar, text = 'ASSIGN EVENTS', width = 15, bg = 'RoyalBlue2', fg = 'white', borderwidth=0)
        AssignBtn.pack(side = 'left', padx = 0, pady = 0)
        toolbar.pack(side = 'top', fill = 'x')

#-----Second Class------
class AddPart(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.top_tool()
        self.main_heading("Home")

    def main_heading(self, heading):
        main_label = tk.Label(self, text = heading, font = LARGE_FONT, fg = 'white', bg = 'RoyalBlue1', width = 1000, height = 4)
        main_label.pack(side = 'top')

您是否尝试继承基类? class AddPart(MainPage):

而不是class AddPart(tk.Frame, MainPage):因为MainPage已经是tk.Frame

遗产

我想在另一个类AddPart中使用MainPage类中的所有函数

这就是继承的用途。 正如@progmatico@mondlos指出的那样,通过继承AddPart MainPage ,您将可以访问所有基类函数。

看来您的两个类都具有依赖于该类的函数(除非我误解了所使用的tk模块),因此使用诸如静态方法之类的方法将无法正常工作。

从您的评论中,您将得到TypeError: Cannot create a consistent method resolution order (MRO) for bases尝试@mondlos建议时无法TypeError: Cannot create a consistent method resolution order (MRO) for bases错误TypeError: Cannot create a consistent method resolution order (MRO) for bases 这是因为您从MainPage继承了tk.Frame类型,该类型也包含在AddPart 进行@progmatico建议的操作应该可以。 有几个答案表明双继承会在此SO问题上引起此问题: TypeError:无法创建一致的方法解析顺序(MRO)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM