I'm creating a wxPython soundboard and was wondering how to implement an About Box. The goal is to press an About button on the wxPython File menu and generate an About Box.
This is my code so far:
import wx
import os
import pygame
pygame.init()
##SOUNDS##
goliathwav = pygame.mixer.Sound("goliath.wav")
channelopen = pygame.mixer.Sound("channelopen.wav")
##SOUNDS##
class windowClass(wx.Frame):
def __init__(self, *args, **kwargs):
super(windowClass,self).__init__(*args,**kwargs)
self.__basicGUI()
def __basicGUI(self):
panel = wx.Panel(self)
menuBar = wx.MenuBar()
fileButton = wx.Menu()
editButton = wx.Menu()
aboutBox = wx.MessageDialog(None, "Created by Kommander000(cyrex)")
answer=aboutBox.ShowModal()
aboutBox.Destroy()
aboutButton = wx.Menu()
exitItem = fileButton.Append(wx.ID_EXIT, 'Exit','status msg...')
aboutItem = aboutButton.Append(wx.ID_ABOUT, "About")
menuBar.Append(fileButton, 'File')
menuBar.Append(editButton, 'Edit')
menuBar.Append(aboutButton, 'About this program')
self.SetMenuBar(menuBar)
self.Bind(wx.EVT_MENU, self.__quit, exitItem)
self.Bind(wx.EVT_MENU, self.OnMenuHelpAbout, aboutBox)
self.__sound_dict = { "Goliath" : "goliath.wav",
"Goliath2" : "channelopen.wav"
}
self.__sound_list = sorted(self.__sound_dict.keys())
self.__list = wx.ListBox(panel,pos=(20,20), size=(250,150))
for i in self.__sound_list:
self.__list.Append(i)
self.__list.Bind(wx.EVT_LISTBOX,self.__on_click)
#wx.TextCtrl(panel,pos=(10,10), size=(250,150))
self.SetTitle("Soundboard")
self.Show(True)
def __on_click(self,event):
event.Skip()
name = self.__sound_list[self.__list.GetSelection()]
filename = self.__sound_dict[name]
if filename == "goliath.wav":
print "[ NOW PLAYING ] ... %s" % filename
pygame.mixer.Sound.play(goliathwav)
if filename == "channelopen.wav":
print "[ NOW PLAYING ] ... %s" % filename
pygame.mixer.Sound.play(channelopen)
def __quit(self, e):
self.Close()
def main():
app = wx.App()
windowClass(None, -1, style=wx.MAXIMIZE_BOX | wx.CAPTION | wx.CENTRE)
app.MainLoop()
main()
This is the error I am receiving:
self.Bind(wx.EVT_MENU, self.OnMenuHelpAbout, aboutBox)
AttributeError: 'windowClass' object has no attribute 'OnMenuHelpAbout'
Any suggestions?
Thanks as always,
kommander000
wx python has its own wx.AboutBox() used in conjunction with wx.AboutDialogInfo()
def About(self, event):
from platform import platform
myos = platform()
aboutInfo = wx.AboutDialogInfo()
aboutInfo.SetName("My Application ")
aboutInfo.SetVersion("1.0")
aboutInfo.SetDescription("My Super App," \
" That does amazing things\nRunning on: "+myos)
aboutInfo.SetCopyright("(C) Joe Bloggs-2016")
aboutInfo.SetLicense("https://www.gnu.org/licenses/gpl-2.0.html")
aboutInfo.AddDeveloper("Joe Bloggs")
aboutInfo.AddDocWriter("Joe Bloggs")
aboutInfo.SetWebSite('https://www.JoeBlogs.com')
wx.AboutBox(aboutInfo)
See:https://wxpython.org/docs/api/wx-module.html#AboutBox
you again :)
The aboutBox needs to be created in your missing callback OnMenuHelpAbout (that I refactored to make private as stated in my previous answer)
Also (not related) but I have changed the dictionary so it directly points to the sound object: no more if/elif, you can load 200 sounds the code will still be the same.
Fixed code:
import wx
import os
import pygame
pygame.init()
##SOUNDS##
##SOUNDS##
class windowClass(wx.Frame):
__goliathwav = pygame.mixer.Sound("goliath.wav")
__channelopen = pygame.mixer.Sound("channelopen.wav")
def __init__(self, *args, **kwargs):
super(windowClass,self).__init__(*args,**kwargs)
self.__basicGUI()
def __basicGUI(self):
panel = wx.Panel(self)
menuBar = wx.MenuBar()
fileButton = wx.Menu()
editButton = wx.Menu()
aboutButton = wx.Menu()
exitItem = fileButton.Append(wx.ID_EXIT, 'Exit','status msg...')
aboutItem = aboutButton.Append(wx.ID_ABOUT, "About")
menuBar.Append(fileButton, 'File')
menuBar.Append(editButton, 'Edit')
menuBar.Append(aboutButton, 'About this program')
self.SetMenuBar(menuBar)
self.Bind(wx.EVT_MENU, self.__quit, exitItem)
self.Bind(wx.EVT_MENU, self.__onmenuhelpabout, aboutItem)
self.__sound_dict = { "Goliath" : self.__goliathwav,
"Goliath2" : self.__channelopen
}
self.__sound_list = sorted(self.__sound_dict.keys())
self.__list = wx.ListBox(panel,pos=(20,20), size=(250,150))
for i in self.__sound_list:
self.__list.Append(i)
self.__list.Bind(wx.EVT_LISTBOX,self.__on_click)
#wx.TextCtrl(panel,pos=(10,10), size=(250,150))
self.SetTitle("Soundboard")
self.Show(True)
def __onmenuhelpabout(self,event):
event.Skip()
aboutBox = wx.MessageDialog(None, "Created by Kommander000(cyrex)")
answer=aboutBox.ShowModal()
aboutBox.Destroy()
def __on_click(self,event):
event.Skip()
name = self.__sound_list[self.__list.GetSelection()]
sound = self.__sound_dict[name]
print("[ NOW PLAYING ] ... %s" % name)
pygame.mixer.Sound.play(sound)
def __quit(self, e):
self.Close()
def main():
app = wx.App()
windowClass(None, -1, style=wx.MAXIMIZE_BOX | wx.CAPTION | wx.CENTRE)
app.MainLoop()
main()
def __quit(self, e):
self.Close()
def main():
app = wx.App()
windowClass(None, -1, style=wx.MAXIMIZE_BOX | wx.CAPTION | wx.CENTRE)
app.MainLoop()
main()
Related
The following is a bit of copied code from another question, it works fine as a standalone app, but the pop-up right-click menu references frame_1 which is not available if "if name == 'main':" is false, as it is when the program is called by another. What should this reference be changed to?
Thanks.
import wx
import sys
sys.path.append("..")
from ObjectListView import ObjectListView, ColumnDefn
### 2. Launcher creates wxMenu. ###
menu_titles = [ "Open",
"Properties",
"Rename",
"Delete" ]
menu_title_by_id = {}
for title in menu_titles:
menu_title_by_id[ wx.NewId() ] = title
class Track(object):
"""
Simple minded object that represents a song in a music library
"""
def __init__(self, title, artist, album):
self.title = title
self.artist = artist
self.album = album
def GetTracks():
"""
Return a collection of tracks
"""
return [
Track("Sweet Lullaby", "Deep Forest", "Deep Forest"),
Track("Losing My Religion", "U2", "Out of Time"),
Track("En el Pais de la Libertad", "Leon Gieco", "Leon Gieco"),
]
class MyFrame(wx.Frame):
def __init__(self, *args, **kwds):
wx.Frame.__init__(self, *args, **kwds)
self.Init()
def Init(self):
self.InitModel()
self.InitWidgets()
self.InitObjectListView()
def InitModel(self):
self.songs = GetTracks()
def InitWidgets(self):
panel = wx.Panel(self, -1)
sizer_1 = wx.BoxSizer(wx.VERTICAL)
sizer_1.Add(panel, 1, wx.ALL | wx.EXPAND)
self.SetSizer(sizer_1)
self.myOlv = ObjectListView(panel, -1, style=wx.LC_REPORT | wx.SUNKEN_BORDER)
sizer_2 = wx.BoxSizer(wx.VERTICAL)
sizer_2.Add(self.myOlv, 1, wx.ALL | wx.EXPAND, 4)
panel.SetSizer(sizer_2)
self.Layout()
def InitObjectListView(self):
self.myOlv.SetColumns([
ColumnDefn("Title", "left", 120, "title"),
ColumnDefn("Artist", "left", 100, "artist"),
ColumnDefn("Album", "left", 100, "album")
])
self.myOlv.SetObjects(self.songs)
self.myOlv.Bind(wx.EVT_LIST_ITEM_RIGHT_CLICK, self.RightClick)
def RightClick(self, event):
# record what was clicked
self.list_item_clicked = self.myOlv.GetSelectedObject()
menu = wx.Menu()
menu.Bind(wx.EVT_MENU, self.MenuSelectionCb)
for (id_, title) in menu_title_by_id.items():
### 3. Launcher packs menu with Append. ###
menu.Append(id_, title)
### 5. Launcher displays menu with call to PopupMenu, invoked on the source component, passing event's GetPoint. ###
# self.frame.PopupMenu( menu, event.GetPoint() )
frame_1.PopupMenu(menu, event.GetPoint())
menu.Destroy() # destroy to avoid mem leak
def MenuSelectionCb(self, event):
# do something
operation = menu_title_by_id[ event.GetId() ]
target = self.list_item_clicked.title
print 'Perform "%(operation)s" on "%(target)s."' % vars()
class MyPopupMenu(wx.Menu):
def __init__(self, parent):
super(MyPopupMenu, self).__init__()
self.parent = parent
mmi = wx.MenuItem(self, wx.NewId(), 'Minimize')
self.AppendItem(mmi)
self.Bind(wx.EVT_MENU, self.OnMinimize, mmi)
cmi = wx.MenuItem(self, wx.NewId(), 'Close')
self.AppendItem(cmi)
self.Bind(wx.EVT_MENU, self.OnClose, cmi)
def OnMinimize(self, e):
self.parent.Iconize()
def OnClose(self, e):
self.parent.Close()
if __name__ == '__main__':
app = wx.App(True)
wx.InitAllImageHandlers()
frame_1 = MyFrame(None, -1, "ObjectListView Track Test")
app.SetTopWindow(frame_1)
frame_1.Show()
app.MainLoop()
If you are going to import your code into another module, then you will just need to instantiate that frame in your new main application's code. Let's save your code as olv_tracks.py. Now import it like I do in the following code:
import wx
import olv_tracks
class MyFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, title='Main App')
panel = wx.Panel(self)
self.Show()
# show other frame
frame = olv_tracks.MyFrame(None, -1, "ObjectListView Track Test")
frame.Show()
if __name__ == '__main__':
app = wx.App(False)
frame = MyFrame()
app.MainLoop()
Now you just instantiate the frame the same way you did in your code.
Also, you need to change the reference to frame_1 in your RightClick method to self. So instead of frame_1.PopupMenu(menu, event.GetPoint()), it should be self.PopupMenu(menu, event.GetPoint())
I want to open a TextEntryDialog, when user clicks the button. So if i have a button in the parent frame which i am going to bind this way:
self.Bind(wx.EVT_BUTTON, self.OnAddNew, self.add_new_btn)
Now i have to open a TextEntryDialog when user clicks the button add_new. I want to make textentrydialog somewthing like this
Python, Using wxPython to get multiple input from user
How can i do that? Do i need to just paste that code in ` def OnAddNew(self, event):
Here is the pastebin link to my code: https://pastebin.com/UEYscgFa
I have created class inside a function, so is it possible to do in that way?
NO!
GetData is a class in its own right.
That code already provides you with the method.
The MyFrame is all fluff, to create a standalone working example.
def OnButton(self,event):
dlg = GetData(parent = self.panel)
dlg.ShowModal()
if dlg.result_name:
self.log.AppendText("Name: "+dlg.result_name+"\n")
self.log.AppendText("Surname: "+dlg.result_surname+"\n")
self.log.AppendText("Nickname: "+dlg.result_nickname+"\n")
else:
self.log.AppendText("No Input found\n")
dlg.Destroy()
Edit: I don't understand where the instructions in my comments eluded you but for my sins, here is your code cleaned up and edited as in the comments.
import sqlite3
import wx
import os
class Example(wx.Frame):
def __init__(self, parent, title):
super(Example, self).__init__(parent, title=title, size=(1000,800))
self.inter_list = list()
self.plot_list = list()
self.InitUI()
self.Layout()
self.Centre()
self.Show()
def InitUI(self):
self.p = wx.Panel(self)
bs = wx.BoxSizer(wx.VERTICAL)
gs = wx.GridSizer(10, 18, 5, 5)
bs.Add(gs, 1, wx.EXPAND)
self.search_btn=wx.Button(self.p,-1,"Search!")
self.search_btn.Bind(wx.EVT_BUTTON, self.OnSearch, self.search_btn)
bs.Add(self.search_btn,0,wx.ALIGN_CENTER)
self.p.SetSizer(bs)
def OnSearch(self, event):
dlg = GetData(parent = self.p)
dlg.ShowModal()
if dlg.result_name:
print "Name: "+dlg.result_name+"\n"
print "Surname: "+dlg.result_surname+"\n"
print "Nickname: "+dlg.result_nickname+"\n"
else:
print "No Input found\n"
dlg.Destroy()
class GetData(wx.Dialog):
def __init__(self, parent):
wx.Dialog.__init__(self, parent, wx.ID_ANY, "Name Input", size= (650,220))
self.p = wx.Panel(self,wx.ID_ANY)
self.lblname = wx.StaticText(self.p, label="Name", pos=(20,20))
self.name = wx.TextCtrl(self.p, value="", pos=(110,20), size=(500,-1))
self.lblsur = wx.StaticText(self.p, label="Surname", pos=(20,60))
self.surname = wx.TextCtrl(self.p, value="", pos=(110,60), size=(500,-1))
self.lblnick = wx.StaticText(self.p, label="Nickname", pos=(20,100))
self.nickname = wx.TextCtrl(self.p, value="", pos=(110,100), size=(500,-1))
self.saveButton =wx.Button(self.p, label="Save", pos=(110,160))
self.closeButton =wx.Button(self.p, label="Cancel", pos=(210,160))
self.saveButton.Bind(wx.EVT_BUTTON, self.SaveConnString)
self.closeButton.Bind(wx.EVT_BUTTON, self.OnQuit)
self.Bind(wx.EVT_CLOSE, self.OnQuit)
self.Show()
def OnQuit(self, event):
self.result_name = None
self.Destroy()
def SaveConnString(self, event):
self.result_name = self.name.GetValue()
self.result_surname = self.surname.GetValue()
self.result_nickname = self.nickname.GetValue()
self.Destroy()
app = wx.App()
Example(None, title = 'Raman Spectroscopy Database')
app.MainLoop()
I am trying to get a simple media player working (scipt below) on Python 2.7.11, Wxpython, with MplayerCtrl on Mac 10.11.4, I just compiled the latest MPlayer 1.3.0, but when opening an mp4 video file I get the below error message, Mplayer opens independently (not in the player window) and also XQuartz opens for some reason, heres the error message:
Traceback (most recent call last):
File "/Users/me/Python/MediaPlayer/mediaplayer.py", line 124, in on_add_file
self.playbackSlider.SetRange(0, t_len)
File "/usr/local/lib/wxPython-3.0.2.0/lib/python2.7/site-packages/wx-3.0-osx_cocoa/wx/_controls.py", line 2866, in SetRange
return _controls_.Slider_SetRange(*args, **kwargs)
TypeError: in method 'Slider_SetRange', expected argument 3 of type 'int'
I have MPlayer 1.3.0 in the same directory as the .py script.
Here is the script I am using:
import os
import time
import wx
import MplayerCtrl as mpc
import wx.lib.buttons as buttons
dirName = os.path.dirname(os.path.abspath(__file__))
bitmapDir = os.path.join(dirName, 'bitmaps')
class Frame(wx.Frame):
#----------------------------------------------------------------------
def __init__(self, parent, id, title, mplayer):
wx.Frame.__init__(self, parent, id, title)
self.panel = wx.Panel(self)
sp = wx.StandardPaths.Get()
self.currentFolder = sp.GetDocumentsDir()
self.currentVolume = 50
self.create_menu()
# create sizers
mainSizer = wx.BoxSizer(wx.VERTICAL)
controlSizer = self.build_controls()
sliderSizer = wx.BoxSizer(wx.HORIZONTAL)
self.mplayer = mpc.MplayerCtrl(self.panel, -1, mplayer)
self.playbackSlider = wx.Slider(self.panel, size=wx.DefaultSize)
sliderSizer.Add(self.playbackSlider, 1, wx.ALL|wx.EXPAND, 5)
# create volume control
self.volumeCtrl = wx.Slider(self.panel)
self.volumeCtrl.SetRange(0, 100)
self.volumeCtrl.SetValue(self.currentVolume)
self.volumeCtrl.Bind(wx.EVT_SLIDER, self.on_set_volume)
controlSizer.Add(self.volumeCtrl, 0, wx.ALL, 5)
# create track counter
self.trackCounter = wx.StaticText(self.panel, label="00:00")
sliderSizer.Add(self.trackCounter, 0, wx.ALL|wx.CENTER, 5)
# set up playback timer
self.playbackTimer = wx.Timer(self)
self.Bind(wx.EVT_TIMER, self.on_update_playback)
mainSizer.Add(self.mplayer, 1, wx.ALL|wx.EXPAND, 5)
mainSizer.Add(sliderSizer, 0, wx.ALL|wx.EXPAND, 5)
mainSizer.Add(controlSizer, 0, wx.ALL|wx.CENTER, 5)
self.panel.SetSizer(mainSizer)
self.Bind(mpc.EVT_MEDIA_STARTED, self.on_media_started)
self.Bind(mpc.EVT_MEDIA_FINISHED, self.on_media_finished)
self.Bind(mpc.EVT_PROCESS_STARTED, self.on_process_started)
self.Bind(mpc.EVT_PROCESS_STOPPED, self.on_process_stopped)
self.Show()
self.panel.Layout()
#----------------------------------------------------------------------
def build_btn(self, btnDict, sizer):
""""""
bmp = btnDict['bitmap']
handler = btnDict['handler']
img = wx.Bitmap(os.path.join(bitmapDir, bmp))
btn = buttons.GenBitmapButton(self.panel, bitmap=img,
name=btnDict['name'])
btn.SetInitialSize()
btn.Bind(wx.EVT_BUTTON, handler)
sizer.Add(btn, 0, wx.LEFT, 3)
#----------------------------------------------------------------------
def build_controls(self):
"""
Builds the audio bar controls
"""
controlSizer = wx.BoxSizer(wx.HORIZONTAL)
btnData = [{'bitmap':'player_pause.png',
'handler':self.on_pause, 'name':'pause'},
{'bitmap':'player_stop.png',
'handler':self.on_stop, 'name':'stop'}]
for btn in btnData:
self.build_btn(btn, controlSizer)
return controlSizer
#----------------------------------------------------------------------
def create_menu(self):
"""
Creates a menu
"""
menubar = wx.MenuBar()
fileMenu = wx.Menu()
add_file_menu_item = fileMenu.Append(wx.NewId(), "&Add File", "Add Media File")
menubar.Append(fileMenu, '&File')
self.SetMenuBar(menubar)
self.Bind(wx.EVT_MENU, self.on_add_file, add_file_menu_item)
#----------------------------------------------------------------------
def on_add_file(self, event):
"""
Add a Movie and start playing it
"""
wildcard = "Media Files (*.*)|*.*"
dlg = wx.FileDialog(
self, message="Choose a file",
defaultDir=self.currentFolder,
defaultFile="",
wildcard=wildcard,
style=wx.OPEN | wx.CHANGE_DIR
)
if dlg.ShowModal() == wx.ID_OK:
path = dlg.GetPath()
self.currentFolder = os.path.dirname(path[0])
trackPath = '"%s"' % path.replace("\\", "/")
self.mplayer.Loadfile(trackPath)
t_len = self.mplayer.GetTimeLength()
self.playbackSlider.SetRange(0, t_len)
self.playbackTimer.Start(100)
#----------------------------------------------------------------------
def on_media_started(self, event):
print 'Media started!'
#----------------------------------------------------------------------
def on_media_finished(self, event):
print 'Media finished!'
self.playbackTimer.Stop()
#----------------------------------------------------------------------
def on_pause(self, event):
""""""
if self.playbackTimer.IsRunning():
print "pausing..."
self.mplayer.Pause()
self.playbackTimer.Stop()
else:
print "unpausing..."
self.mplayer.Pause()
self.playbackTimer.Start()
#----------------------------------------------------------------------
def on_process_started(self, event):
print 'Process started!'
#----------------------------------------------------------------------
def on_process_stopped(self, event):
print 'Process stopped!'
#----------------------------------------------------------------------
def on_set_volume(self, event):
"""
Sets the volume of the music player
"""
self.currentVolume = self.volumeCtrl.GetValue()
self.mplayer.SetProperty("volume", self.currentVolume)
#----------------------------------------------------------------------
def on_stop(self, event):
""""""
print "stopping..."
self.mplayer.Stop()
self.playbackTimer.Stop()
#----------------------------------------------------------------------
def on_update_playback(self, event):
"""
Updates playback slider and track counter
"""
try:
offset = self.mplayer.GetTimePos()
except:
return
print offset
mod_off = str(offset)[-1]
if mod_off == '0':
print "mod_off"
offset = int(offset)
self.playbackSlider.SetValue(offset)
secsPlayed = time.strftime('%M:%S', time.gmtime(offset))
self.trackCounter.SetLabel(secsPlayed)
#----------------------------------------------------------------------
if __name__ == "__main__":
import os, sys
paths = [r'./mplayer',
r'./mplayer']
mplayerPath = None
for path in paths:
if os.path.exists(path):
mplayerPath = path
if not mplayerPath:
print "mplayer not found!"
sys.exit()
app = wx.App(redirect=False)
frame = Frame(None, -1, 'MediaPlayer Using MplayerCtrl', mplayerPath)
app.MainLoop()
I am keen on using MPlayer for its flexibility.
I'm new programming interfaces. I'm creating a simple interface with wxpython and openCV to open an image, save it and close the interface. You can see my code below. I can open an image and close the interface. Even, I show dialog boxes for the opening and saving routines but saving is where I have problems. I don't know how to send to OnSave the img (image object) to be saved. This is not clear to me. Can you help me? Thanks in advance.
import wx
import cv2
class MyMenu(wx.Frame):
def __init__(self, parent, id, title):
wx.Frame.__init__(self, parent, id, title, wx.DefaultPosition, wx.Size(200, 150))
menubar = wx.MenuBar()
file = wx.Menu()
edit = wx.Menu()
help = wx.Menu()
file.Append(101, '&Open', 'Open a new document')
file.Append(102, '&Save', 'Save the document')
file.AppendSeparator()
quit = wx.MenuItem(file, 105, '&Quit\tCtrl+Q', 'Quit the Application')
file.AppendItem(quit)
menubar.Append(file, '&File')
menubar.Append(edit, '&Edit')
menubar.Append(help, '&Help')
self.SetMenuBar(menubar)
self.CreateStatusBar()
self.Bind(wx.EVT_MENU, self.OnOpen, id=101)
self.Bind(wx.EVT_MENU, self.OnSave, id=102)
self.Bind(wx.EVT_MENU, self.OnQuit, id=105)
def OnOpen(self, event):
openFileDialog = wx.FileDialog(self, "Open", "", "",
"PNG files (*.png)|*.png|BMP files (*.bmp)|*.bmp",
wx.FD_OPEN | wx.FD_FILE_MUST_EXIST)
openFileDialog.ShowModal()
path = openFileDialog.GetPath()
openFileDialog.Destroy()
img = cv2.imread(str(path))
cv2.imshow('img', img)
return img
def OnSave(self, event):
saveFileDialog = wx.FileDialog(self, "Save As", "", "",
"PNG files (*.png)|*.png|BMP files (*.bmp)|*.bmp",
wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT)
saveFileDialog.ShowModal()
path_save = saveFileDialog.GetPath()
print path_save
saveFileDialog.Destroy()
cv2.imwrite(str(path_save), img)
def OnQuit(self, event):
self.Close()
class MyApp(wx.App):
def OnInit(self):
frame = MyMenu(None, -1, 'menu1.py')
frame.Show(True)
return True
app = MyApp(0)
app.MainLoop()
I get the following error:
NameError: global name 'img' is not defined
EDIT (final version):
import wx
import cv2
import numpy as np
class MyMenu(wx.Frame):
def __init__(self, parent, id, title):
wx.Frame.__init__(self, parent, id, title, wx.DefaultPosition, wx.Size(200, 150))
img = np.array([0])
menubar = wx.MenuBar()
file = wx.Menu()
edit = wx.Menu()
help = wx.Menu()
file.Append(101, '&Open', 'Open a new document')
file.Append(102, '&Save', 'Save the document')
file.AppendSeparator()
quit = wx.MenuItem(file, 105, '&Quit\tCtrl+Q', 'Quit the Application')
file.AppendItem(quit)
menubar.Append(file, '&File')
menubar.Append(edit, '&Edit')
menubar.Append(help, '&Help')
self.SetMenuBar(menubar)
self.CreateStatusBar()
self.Bind(wx.EVT_MENU, self.OnOpen, id=101)
self.Bind(wx.EVT_MENU, self.OnSave, id=102)
self.Bind(wx.EVT_MENU, self.OnQuit, id=105)
def OnOpen(self, event):
openFileDialog = wx.FileDialog(self, "Open", "", "",
"PNG files (*.png)|*.png|BMP files (*.bmp)|*.bmp",
wx.FD_OPEN | wx.FD_FILE_MUST_EXIST)
openFileDialog.ShowModal()
path = openFileDialog.GetPath()
openFileDialog.Destroy()
self.img = cv2.imread(str(path))
cv2.imshow('img', self.img)
def OnSave(self, event):
saveFileDialog = wx.FileDialog(self, "Save As", "", "",
"PNG files (*.png)|*.png|BMP files (*.bmp)|*.bmp",
wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT)
saveFileDialog.ShowModal()
path_save = saveFileDialog.GetPath()
print path_save
saveFileDialog.Destroy()
cv2.imwrite(str(path_save), self.img)
def OnQuit(self, event):
self.Close()
class MyApp(wx.App):
def OnInit(self):
frame = MyMenu(None, -1, 'menu1.py')
frame.Show(True)
return True
app = MyApp(0)
app.MainLoop()
Looking at it you mean the img used in OnSave, if you look, img isn't defined in the scope, nor is it globally defined.
I'm trying to learn wxpython and im never programming before my life.
This application with listctrl and dirdialog.
But then i want to add folders to the listctrl (or is it the listctrl I should use?)
How do i do it?
Or am I doing it the wrong way?
Anyway, here is the code.
# -*- coding: cp1252 -*-
import os
import wx
# Menu ID
ID_QUIT=1
ID_ABOUT=2
ID_ADD=3
class Frame(wx.Frame):
def __init__(self, parent, id, title,):
wx.Frame.__init__(self, parent,id , title, size=(700, 750),)
self.Center()
self.Show()
self.CreateStatusBar()
self.SetStatusText("Status bar") #Statusbar in the bottom of the window
panel = wx.Panel(self, id)
#Listctrl
self.index = 0
self.list_ctrl = wx.ListCtrl(panel, size=(400,600),
style=wx.LC_REPORT
|wx.SUNKEN_BORDER
)
self.list_ctrl.InsertColumn(2, 'Name',width = 401)
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(self.list_ctrl, 0, wx.ALL|wx.TOP, 30)
panel.SetSizer(sizer)
#Menu
menuBar = wx.MenuBar()
filemenu = wx.Menu()
helpmenu = wx.Menu()
filemenu.Append(ID_ADD,"&Add\tCtrl+A", "Adding directory")
filemenu.Append(ID_QUIT, "&Quit\tCtrl+Q", "Quit application")
helpmenu.Append(ID_ABOUT, "&About\tCtrl+A", "About application")
menuBar.Append(filemenu, "&File")
menuBar.Append(helpmenu, "&Help")
self.SetMenuBar(menuBar)
#Event
wx.EVT_MENU(self, ID_ADD, self.onDir)
self.Bind(wx.EVT_MENU, self.QuitWindow, id=ID_QUIT)
self.Bind(wx.EVT_MENU, self.OnAboutBox, id=ID_ABOUT)
# DirDialog
self.currentDirectory = os.getcwd()
dirDlgBtn = wx.Button(panel, label="Add", pos=(600, 10), size=(60, 30))
dirDlgBtn.Bind(wx.EVT_BUTTON, self.onDir)
def onDir(self, event):
"""
Show the DirDialog and print the user's choice to stdout
"""
dlg = wx.DirDialog(self, "Choose a directory:",
style=wx.DD_DEFAULT_STYLE
#| wx.DD_DIR_MUST_EXIST
#| wx.DD_CHANGE_DIR
)
if dlg.ShowModal() == wx.ID_OK:
print "You chose %s" % dlg.GetPath()
dlg.Destroy()
# END
def QuitWindow(self, event):
self.Destroy()
def OnAboutBox(self, event):
description = "text"
licence = "text"
info = wx.AboutDialogInfo()
info.SetName ('text')
info.SetVersion ('0.1')
info.SetDescription(description)
info.SetCopyright ('text')
info.SetLicence(licence)
wx.AboutBox(info)
class App(wx.App):
def OnInit(self):
frame = Frame(None, -1, title = "Film")
frame.Show(1+1==2)
self.SetTopWindow(frame)
return True
app = App(0)
app.MainLoop()
Assuming you want to insert the folder name into the listctrl, a clean approach would be to write a small function and call it from your onDir function:
def onDir(self, event):
"""
Show the DirDialog and print the user's choice to stdout
"""
dlg = wx.DirDialog(self, "Choose a directory:",
style=wx.DD_DEFAULT_STYLE
#| wx.DD_DIR_MUST_EXIST
#| wx.DD_CHANGE_DIR
)
if dlg.ShowModal() == wx.ID_OK:
path = dlg.GetPath()
print "You chose %s" % path
self.AddToList(path)
dlg.Destroy()
def AddToList(self, path):
fname = os.path.basename(path) # insert only folder-name
self.list_ctrl.Append(fname)