2016-05-15

【備忘録】ListBox のアイテムにポップアップメニュー ─ wxPython

ListBox のアイテムにオブジェクト(インスタンス)を表示することができましたので [1]、さらにポップアップメニューを付けてみました [2]

動作環境は次の通りです。

  • OS: Fedora 24 (x86_64, Beta)
  • python-2.7.11-4.fc24.x86_64
  • wxPython-3.0.2.0-10.fc24.x86_64
  • IDE: eclipse-pydev-4.6.0-1.fc24.x86_64
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# -*- coding: utf-8 -*-
import wx
 
ID_CAPITAL = wx.NewId()
 
class MyFrame(wx.Frame):
 
    def __init__(self, parent):
        wx.Frame.__init__(self, parent, title=u"都道府県リスト", size=(250, 200))
        self.CreateStatusBar()
        self.create_listbox()
        self.createMenu()
 
    def create_listbox(self):
        self.lbox = wx.ListBox(self, wx.ID_ANY)
        self.lbox.Bind(wx.EVT_CONTEXT_MENU, self.showPopupMenu)
 
        elem_01 = PrefObj(u"北海道", u"札幌市")
        self.lbox.Append(elem_01.pref, elem_01)
 
        elem_02 = PrefObj(u"青森県", u"青森市")
        self.lbox.Append(elem_02.pref, elem_02)
 
        elem_03 = PrefObj(u"岩手県", u"盛岡市")
        self.lbox.Append(elem_03.pref, elem_03)
 
    def createMenu(self):
        self.menu = wx.Menu()
        item_capital = wx.MenuItem(self.menu, ID_CAPITAL,  u"県庁所在地")
        self.menu.AppendItem(item_capital)
        self.Bind(wx.EVT_MENU, self.OnCapital, id=ID_CAPITAL)
         
    def showPopupMenu(self,evt):
        position = self.ScreenToClient(wx.GetMousePosition())
        self.PopupMenu(self.menu,position)
 
    def OnCapital(self, event):
        obj = self.lbox.GetClientData(self.lbox.GetSelection())
        self.SetStatusText(obj.pref + u"の県庁所在地は" + obj.capital + u"です。")
         
class PrefObj():
    def __init__(self, pref, capital):
        self.pref = pref
        self.capital = capital
 
class MyApp(wx.App):
    def OnInit(self):
        ui = MyFrame(None)
        ui.Show(True)
        return True
 
if __name__ == "__main__":
    app = MyApp(False)
    app.MainLoop()

実行例を以下に示しました。

 

参考サイト

  1. bitWalk's: 【備忘録】ListBox のアイテムにインスタンスを追加 ─ wxPython
  2. Revx At Large: wxPython ListBox PopupMenu

 

ブログランキング・にほんブログ村へ
にほんブログ村

0 件のコメント: