繁体   English   中英

在Python中调用自定义对象的主要方法

[英]Main method to call a custom object in Python

我试图解决与将对象用作参数时对象返回的内容有关的问题。

例如,我有一个自定义对象,我想将其用作另一个tkinter小部件的父对象,因此我需要返回一个tkinter对象,以将新的tkinter对象放入我的自定义对象中,但是我的自定义对象返回的是一个对象自定义类。

我可以用代码更好地解释这一点:

class CustomFrame(object):
    def __init__(self,**args):
        #code that works

        #The next is an external object that have a variable that I need to call externally.
        #The variable is "interior"
        self.externalobject = anotherobject('random')

cfr1 = CustomFrame()

label1 = Label(cfr1)

现在,我想使用“ self.externalobject.interior”作为label1的父级,但是我想使其友好,只需调用“ cfr1”而不是“ self.externalobject.interior”

我知道如果使用call方法并返回所需的值(如果我将“ cfr1”作为函数传递),它将可以使用,但是我想使其尽可能地具有Python风格。

因此,我需要知道是否还有其他特殊方法或某些方法可以修改其返回的内容。

编辑:所以,这是我正在使用的代码的一部分:

这是垂直滚动框架的代码(不是我的代码)。

class VerticalScrolledFrame(Frame):
    """A pure Tkinter scrollable frame that actually works!
    * Use the 'interior' attribute to place widgets inside the scrollable frame
    * Construct and pack/place/grid normally
    * This frame only allows vertical scrolling

    """
    def __init__(self, parent, bg, *args, **kw):
        Frame.__init__(self, parent, *args, **kw)            

        # create a canvas object and a vertical scrollbar for scrolling it
        vscrollbar = Scrollbar(self, orient=VERTICAL)
        canvas = Canvas(self, bd=0, highlightthickness=0,
                        yscrollcommand=vscrollbar.set,bg=bg)
        vscrollbar.config(command=canvas.yview)
        canvas.pack(side=LEFT, fill=BOTH, expand=TRUE)

        # reset the view
        canvas.xview_moveto(0)
        canvas.yview_moveto(0)

        # create a frame inside the canvas which will be scrolled with it
        self.interior = interior = Frame(canvas,bg=bg)
        interior_id = canvas.create_window(0, 0, window=interior,
                                           anchor=NW)

        a = Frame(self.interior,height=10,bg=dynamicBackground())
        a.pack()

        def canvasscroll(event):
            canvas.yview('scroll',int(-1*(event.delta/120)), "units")

        def _configure_canvas(event):
            a.configure(height=10)
            a.update()
            mylist = interior.winfo_children()
            for i in mylist:
                lasty=i.winfo_height()+i.winfo_y()
            a.configure(height=lasty)
            if interior.winfo_reqwidth() != canvas.winfo_width():
                # update the inner frame's width to fill the canvas
                canvas.itemconfigure(interior_id, width=canvas.winfo_width())
            if canvas.winfo_height()<lasty:
                vscrollbar.pack(fill=Y, side=RIGHT, expand=FALSE)
                canvas.config(scrollregion=(0,0,0,lasty))
                canvas.bind_all("<MouseWheel>", canvasscroll)
            else:
                canvas.unbind_all("<MouseWheel>")
                try:
                    vscrollbar.pack_forget()
                except:
                    pass
                canvas.config(scrollregion=(0,0,0,0))


        canvas.bind('<Configure>', _configure_canvas)

这是我的自定义对象的代码:

class UtilityPanel(object):
    def __init__(self,parent='*',title='Main Title',state='normal',bg='red'):
        super().__init__()
        if parent != '*':
            self.parent=parent
        else:
            raise TypeError('You must specify a parent for this widget.')
        self.title=title

        global subpanels

        if len(subpanels) == 0:
            self.panelid = 'sp-1'
            subpanels.append('sp-1')
        else:
            self.panelid = 'sp-'+str(int(subpanels[-1].split('-')[1])+1)
            subpanels.append(self.panelid)

        self.panel = VerticalScrolledFrame(self.parent,bg=bg,width=600,height=200,name=self.panelid)

    def __call__(self,name):
        return(self.panel.interior)

    def pack(self):
        self.panel.place(x=300)
        global activepanel
        activepanel = self.panelid

因此,如果我通过类似label1 = Label(cfr1.panel.interior)的参数,它可以工作,但是我希望它仅通过将cfr1作为参数来使其工作。

我想我了解OP在这里遇到的问题。 他们无法将框架用作其标签的容器,这是因为它们缺少super()并且需要从Frame继承。

更改此:

class CustomFrame(object):
    def __init__(self,**args):

对此:

class CustomFrame(Frame):
    def __init__(self,**args):
        super().__init__()

而且,您应该能够将客户框架用作标签的容器。

根据您在下面的评论,尝试以下操作:

class CustomFrame(anotherobject):
    def __init__(self,**args):
        super().__init__()

这应该继承该对象的所有方法和属性。

您试图隐式将一种对象类型强制转换为另一种类型。

如果您想成为“ pythonic”,请回想一下,

>>> import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
...

暗中做事会引起麻烦。

使用call magic函数获取所需的属性,或开始查看属性和装饰器,我没有发现任何问题。

还有的魔术方法的完整列表在这里

如果创建了自己的tk.Label自定义子类,基本上可以为您解tk.Label ,则可能会实现所需的功能。

(免责声明:我从未使用过tkinter,因此我无法确定它是否在该框架的上下文中真正起作用。该示例只是为了演示我试图在此处概述的概念。)

class CustomLabel(tk.Label):

    def __init__(self, master, **options):
        if isinstance(master, CustomFrame):
            master = master.externalobject.interior
        super().__init__(master=master, **options)

这样,您应该可以使用CustomLabel(cfr1)

但是,我强烈支持@doctorlove在回答中传达的信息。 恕我直言,最Python的方式确实是Label(cfr1.externalobject.interior)使用建议的方法__call__或内部的财产CustomFrame ,提供了一个快捷方式externalobject.interior

@property
def interior(self):
    return self.externalobject.interior

你会这样使用Label(crf1.interior)

暂无
暂无

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

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