wxpython.orgにPopupMenu方法のセクションを読む
「が このウィンドウを相対 指定された座標で指定されたメニューをポップアップ表示し、戻るは、ユーザが却下した場合 制御メニュー。 メニュー項目が選択された場合、 対応するメニューイベントが 生成され、通常通り処理される。 デフォルト位置がマウスカーソルの 現在位置次いで、指定された場合に使用されます。」
チェックツールのEVT_MENUイベントにバインドする必要があります。ツールボタンがチェックされたら、メニューをポップアップすることができます。ポップアップの位置を指定しないと、マウスの現在の位置が使用されます。これは必要なものです。
メニューはマウスとは独立して所定の場所にポップアップ表示したい場合は、あなたがのは、コードを見てみましょう、ツールバーの画面の位置を取得し、オフセット
を追加することができます。
[:ツール上の任意の点の位置を計算する方法を示すために、ツールをクリックするとツールバー上のさまざまな点を計算して表示するようにコードを修正しました。メニューは、クリックされたボタンの右下隅に表示されます。それはWindows上で私のために働く。私はそれが他のプラットフォームで動作しない場合は知って興味があります。このコードの
import wx
class ViewApp(wx.App):
def OnInit(self):
self.frame = ToolFrame(None, -1, "Test App")
self.frame.Show(True)
return True
class MyPopupMenu(wx.Menu):
def __init__(self, parent):
wx.Menu.__init__(self)
self.parent = parent
minimize = wx.MenuItem(self, wx.NewId(), 'Minimize')
self.AppendItem(minimize)
self.Bind(wx.EVT_MENU, self.OnMinimize, id=minimize.GetId())
def OnMinimize(self, event):
self.parent.Iconize()
class ToolFrame(wx.Frame):
def __init__(self, parent, id, title):
wx.Frame.__init__(self, parent, id, title, size=(350, 250))
self.toolbar = self.CreateToolBar()
self.tool_id = wx.NewId()
for i in range(3):
tool_id = wx.NewId()
self.toolbar.AddCheckLabelTool(tool_id, 'Tool', wx.EmptyBitmap(10,10))
self.toolbar.Bind(wx.EVT_MENU, self.OnTool, id=tool_id)
self.toolbar.Realize()
self.Centre()
self.Show()
def OnTool(self, event):
if event.IsChecked():
# Get the position of the toolbar relative to
# the frame. This will be the upper left corner of the first tool
bar_pos = self.toolbar.GetScreenPosition()-self.GetScreenPosition()
# This is the position of the tool along the tool bar (1st, 2nd, 3rd, etc...)
tool_index = self.toolbar.GetToolPos(event.GetId())
# Get the size of the tool
tool_size = self.toolbar.GetToolSize()
# This is the upper left corner of the clicked tool
upper_left_pos = (bar_pos[0]+tool_size[0]*tool_index, bar_pos[1])
# Menu position will be in the lower right corner
lower_right_pos = (bar_pos[0]+tool_size[0]*(tool_index+1), bar_pos[1]+tool_size[1])
# Show upper left corner of first tool in black
dc = wx.WindowDC(self)
dc.SetPen(wx.Pen("BLACK", 4))
dc.DrawCircle(bar_pos[0], bar_pos[1], 4)
# Show upper left corner of this tool in blue
dc.SetPen(wx.Pen("BLUE", 4))
dc.DrawCircle(upper_left_pos[0], upper_left_pos[1], 4)
# Show lower right corner of this tool in green
dc.SetPen(wx.Pen("GREEN", 4))
dc.DrawCircle(lower_right_pos[0], lower_right_pos[1], 4)
# Correct for the position of the tool bar
menu_pos = (lower_right_pos[0]-bar_pos[0],lower_right_pos[1]-bar_pos[1])
# Pop up the menu
self.PopupMenu(MyPopupMenu(self), menu_pos)
if __name__ == "__main__":
app = ViewApp(0)
app.MainLoop()
パーツhereから来ます。
ご返信ありがとうございます。問題は、メニューを開く方法ではなく、ツールバーの個々のツールの位置(回答の「オフセットを追加する」)を取得できないときにどのように配置するかでした。私はこの特定の問題の回避策を見つけましたが、将来的には、ツールバー内のツールの位置を(ピクセル単位で)取得する方法や、それが可能であるかどうかを知りたいと思います。 –
編集を参照してください。クリックされたツールの左上隅と右下隅が表示されます。メニューが右下に表示されます。 – Mathieu
Gnomeを使用してMint Linuxで正常に動作します。 – Alan