【问题标题】:wxpython Accessing an object from an IDwxpython 从 ID 访问对象
【发布时间】:2012-09-21 19:50:52
【问题描述】:

在 wxPython 应用程序中创建的每个对象都会创建一个 id。它可以作为参数给出,也可以使用id=wx.NewId()自动创建。

据我了解,使用对象的 id,您可以从其他地方引用该对象,但我找不到任何简单的解释说明如何完成。

谁能指出我正确的方向或对此有所了解?

(注意:我不希望通过 ID 绑定事件,这是我在各处找到的唯一教程。)

【问题讨论】:

  • 我不确定...我已经广泛使用 wx 很长时间了,从来没有通过 id 获得过...通常您将所有内容封装到可以访问所需内容的类中...您可以在构造函数周围编写某种包装器/工厂函数以将 id 存储在全局字典中以供以后查找 ...

标签: python wxpython python-2.7


【解决方案1】:

免责声明:我从 OPs 问题中提取了这个答案。 Answers should not be contained in the question itself.


答案由Jase提供,但基于answer by Joran Beasley

wx.Window 类中的函数FindWindowById(),大多数小部件都是该类的子类。

通过在对象父对象(尚未尝试祖父对象等)上调用此函数,它会返回相关对象的指针(副本?),这样:(在交互式解释器中)

import wx
app = wx.App()
frame = wx.Frame(None)
but = wx.Button(frame, -1, label='TestButton')
frame2 = wx.Frame(None)

butId = but.GetId()
test = wx.Window.FindWindowById(butId)         # Fails with TypeError
  # TypeError: unbound method FindWindowById() must be called with Window instance as
  # first argument (got int instance instead)
test = Frame2.FindWindowById(butId)            # returned either a None object or nothing at all.
test = Frame.FindWindowById(butId)             # returned a pionter (copy?) of the object in such a
  # manner that the following worked:
label = test.GetLabel()
print label                                    # displayed u'TestButton'

因此,通过知道对象的id,可以获得指向该对象的指针,以便进一步处理它。

【讨论】:

    【解决方案2】:

    我认为没有内置的方法可以做到这一点......但你可以做这样的事情

    my_ids = {}
    
    def widget_factory(widget_class,parent,id,*args,**kwargs):
         w = widget_class(parent,id,*args,**kwargs)
         my_ids[id] = w
    
    def get_widget_by_id(widget_id):
         return my_ids[widget_id]
    

    显然有一个功能......

    http://wxpython.org/docs/api/wx.Window-class.html#FindWindowById

    【讨论】:

    • @joran.. 好的,那么关于链接功能,我将如何称呼它。该函数是类窗口的函数。因此,要获取与 id wxSomeID 关联的窗口...打开 interperator 并尝试自己...愚蠢的评论
    • 所以也许在你的主机上调用它?
    • @joran...大声笑...刚刚尝试了三个版本。一个调用有问题的对象上的函数(冗余,因为如果我们知道有问题的对象没有目的).....两个调用 wx.Window.FindObjectById(###) (它像我一样,因为有没有 Window 类的实例来生成函数调用的自身数据).....三个在父级对象 test=frame.FindWindowById(###) 上调用它(成功)......四个 test=frame2.FindWindowById (###)(第 2 帧不在我们的神秘物体的家谱中)(失败且没有返回(可能返回无???)所以道具并回答你的功劳!谢谢!
    • 很高兴能帮上忙,听起来你明白了 :) ...我真的很喜欢 wx 很棒
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-27
    • 1970-01-01
    • 2020-10-30
    • 2013-01-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多