wxPython中的彈出選單
在本文中,我們將瞭解wxPython,並建立一個程式來製作彈出式選單項。
彈出選單是圖形使用者介面 (GUI),允許我們顯示一些特定的專案和選項。在本教程中,我們將學習如何在wxPython中建立和實現彈出選單。它是一個用於Python語言的GUI工具包,它為我們提供了一組繫結,並允許開發人員建立具有原生介面的跨平臺應用程式。
使用pip命令安裝wxPython
pip install wxPython
如果安裝失敗,請執行以下命令。
pip install -U -f https://extras.wxpython.org/wxPython4/extras/linux/gtk3/ubuntu-18.04/ wxPython
為了顯示訊息框,我們將使用easygui中的messagebox。
要安裝easygui,請執行以下命令。
pip install easygui
EasyGUI
它也是一個圖形使用者介面,它為我們提供了一組預構建的對話方塊和小部件,可以輕鬆使用,而無需像Tkinter或wxPython那樣編寫其核心功能部分的程式碼。使用EasyGUI,我們可以建立更多欄位,例如訊息框、文字欄位、按鈕和其他元件。
示例
import wx
import easygui
class PopUpMenu(wx.Menu):
def __init__(self):
super().__init__()
# Add a menu item
self.item1 = self.Append(wx.ID_ANY, "Mango")
# Bind an event handler to the mango menu item
self.Bind(wx.EVT_MENU, self.mango, self.item1)
# Add another menu item
self.item2 = self.Append(wx.ID_ANY, "Litchi")
# Bind an event handler to the litchi menu item
self.Bind(wx.EVT_MENU, self.litchi, self.item2)
# Add another menu item
self.item3 = self.Append(wx.ID_ANY, "Apple")
# Bind an event handler to the apple menu item
self.Bind(wx.EVT_MENU, self.apple, self.item3)
def mango(self, event):
easygui.msgbox("You choose Mango!", title="msg")
def litchi(self, event):
easygui.msgbox("You choose Litchi!", title="msg")
def apple(self, event):
easygui.msgbox("You choose Apple!", title="msg")
class FrameClass(wx.Frame):
def __init__(self):
super().__init__(None, title="Frame Simple")
# Create a menu bar
self.menubar = wx.MenuBar()
# Add the pop-up menu to the menu bar
self.menubar.Append(PopUpMenu(), "Fruit Menu")
# Set the menu bar as the frame's menu bar
self.SetMenuBar(self.menubar)
# Bind a mouse event handler to the frame
self.Bind(wx.EVT_RIGHT_DOWN, self.on_right_click)
def on_right_click(self, event):
self.PopupMenu(self.menubar, event.GetPosition())
if __name__ == "__main__":
app = wx.App()
# Creating a frame
frame = FrameClass()
# Show the frame
frame.Show()
app.MainLoop()
輸出
解釋
在上面的程式中,我們使用選單欄建立一個框架。當您單擊框架時,將顯示一個彈出選單。在選單欄中,它將有一個水果專案的彈出選單,例如“芒果”、“荔枝”、“蘋果”。當您單擊或選擇選單欄中列出的任何專案時,它將顯示一個包含所選水果專案名稱的訊息作為操作。
在這裡,在PopUpMenu類中,我們正在建立一個彈出選單。該類包含一個建構函式,用於建立一個沒有選單項的彈出選單。在類中,它具有不同名稱的水果名稱的方法。假設您單擊名為“芒果”的專案,那麼它將呼叫名為“mango”的方法,此方法將列印彈出訊息“您選擇了芒果”。同樣,選擇其他選單項將透過呼叫其自身函式來執行相同的操作。
因此,我們瞭解瞭如何在wxPython中建立彈出選單項,以及如何在選擇任何指定的選單項後實現操作。
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP