wx Import Error - python

I am trying to run this code. Previously, it was giving No module wx as an error. Then I downloaded the wx module and now it is giving this error:
Traceback (most recent call last):
File "C:\Python24\player.py", line 2, in -toplevel-
import wx
File "C:\Python24\wx__init__.py", line 45, in -toplevel-
from wxPython import wx
File "C:\Python24\wxPython__init__.py", line 20, in -toplevel-
import wxc
ImportError: DLL load failed: The specified module could not be found.
Here is my code:
import os
import wx
import wx.media
import wx.lib.buttons as buttons
dirName = os.path.dirname(os.path.abspath(__file__))
bitmapDir = os.path.join(dirName, 'bitmaps')
########################################################################
class MediaPanel(wx.Panel):
""""""
#----------------------------------------------------------------------
def __init__(self, parent):
"""Constructor"""
wx.Panel.__init__(self, parent=parent)
self.frame = parent
self.currentVolume = 50
self.createMenu()
self.layoutControls()
sp = wx.StandardPaths.Get()
self.currentFolder = sp.GetDocumentsDir()
self.timer = wx.Timer(self)
self.Bind(wx.EVT_TIMER, self.onTimer)
self.timer.Start(100)
#----------------------------------------------------------------------
def layoutControls(self):
"""
Create and layout the widgets
"""
try:
self.mediaPlayer = wx.media.MediaCtrl(self, style=wx.SIMPLE_BORDER)
except NotImplementedError:
self.Destroy()
raise
# create playback slider
self.playbackSlider = wx.Slider(self, size=wx.DefaultSize)
self.Bind(wx.EVT_SLIDER, self.onSeek, self.playbackSlider)
self.volumeCtrl = wx.Slider(self, style=wx.SL_VERTICAL|wx.SL_INVERSE)
self.volumeCtrl.SetRange(0, 100)
self.volumeCtrl.SetValue(self.currentVolume)
self.volumeCtrl.Bind(wx.EVT_SLIDER, self.onSetVolume)
# Create sizers
mainSizer = wx.BoxSizer(wx.VERTICAL)
hSizer = wx.BoxSizer(wx.HORIZONTAL)
audioSizer = self.buildAudioBar()
# layout widgets
mainSizer.Add(self.playbackSlider, 1, wx.ALL|wx.EXPAND, 5)
hSizer.Add(audioSizer, 0, wx.ALL|wx.CENTER, 5)
hSizer.Add(self.volumeCtrl, 0, wx.ALL, 5)
mainSizer.Add(hSizer)
self.SetSizer(mainSizer)
self.Layout()
#----------------------------------------------------------------------
def buildAudioBar(self):
"""
Builds the audio bar controls
"""
audioBarSizer = wx.BoxSizer(wx.HORIZONTAL)
self.buildBtn({'bitmap':'player_prev.png', 'handler':self.onPrev,
'name':'prev'},
audioBarSizer)
# create play/pause toggle button
img = wx.Bitmap(os.path.join(bitmapDir, "player_play.png"))
self.playPauseBtn = buttons.GenBitmapToggleButton(self, bitmap=img, name="play")
self.playPauseBtn.Enable(False)
img = wx.Bitmap(os.path.join(bitmapDir, "player_pause.png"))
self.playPauseBtn.SetBitmapSelected(img)
self.playPauseBtn.SetInitialSize()
self.playPauseBtn.Bind(wx.EVT_BUTTON, self.onPlay)
audioBarSizer.Add(self.playPauseBtn, 0, wx.LEFT, 3)
btnData = [{'bitmap':'player_stop.png',
'handler':self.onStop, 'name':'stop'},
{'bitmap':'player_next.png',
'handler':self.onNext, 'name':'next'}]
for btn in btnData:
self.buildBtn(btn, audioBarSizer)
return audioBarSizer
#----------------------------------------------------------------------
def buildBtn(self, btnDict, sizer):
""""""
bmp = btnDict['bitmap']
handler = btnDict['handler']
img = wx.Bitmap(os.path.join(bitmapDir, bmp))
btn = buttons.GenBitmapButton(self, bitmap=img, name=btnDict['name'])
btn.SetInitialSize()
btn.Bind(wx.EVT_BUTTON, handler)
sizer.Add(btn, 0, wx.LEFT, 3)
#----------------------------------------------------------------------
def createMenu(self):
"""
Creates a menu
"""
menubar = wx.MenuBar()
fileMenu = wx.Menu()
open_file_menu_item = fileMenu.Append(wx.NewId(), "&Open", "Open a File")
menubar.Append(fileMenu, '&File')
self.frame.SetMenuBar(menubar)
self.frame.Bind(wx.EVT_MENU, self.onBrowse, open_file_menu_item)
#----------------------------------------------------------------------
def loadMusic(self, musicFile):
"""
Load the music into the MediaCtrl or display an error dialog
if the user tries to load an unsupported file type
"""
if not self.mediaPlayer.Load(musicFile):
wx.MessageBox("Unable to load %s: Unsupported format?" % path,
"ERROR",
wx.ICON_ERROR | wx.OK)
else:
self.mediaPlayer.SetInitialSize()
self.GetSizer().Layout()
self.playbackSlider.SetRange(0, self.mediaPlayer.Length())
self.playPauseBtn.Enable(True)
#----------------------------------------------------------------------
def onBrowse(self, event):
"""
Opens file dialog to browse for music
"""
wildcard = "MP3 (*.mp3)|*.mp3|" \
"WAV (*.wav)|*.wav"
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)
self.loadMusic(path)
dlg.Destroy()
#----------------------------------------------------------------------
def onNext(self, event):
"""
Not implemented!
"""
pass
#----------------------------------------------------------------------
def onPause(self):
"""
Pauses the music
"""
self.mediaPlayer.Pause()
#----------------------------------------------------------------------
def onPlay(self, event):
"""
Plays the music
"""
if not event.GetIsDown():
self.onPause()
return
if not self.mediaPlayer.Play():
wx.MessageBox("Unable to Play media : Unsupported format?",
"ERROR",
wx.ICON_ERROR | wx.OK)
else:
self.mediaPlayer.SetInitialSize()
self.GetSizer().Layout()
self.playbackSlider.SetRange(0, self.mediaPlayer.Length())
event.Skip()
#----------------------------------------------------------------------
def onPrev(self, event):
"""
Not implemented!
"""
pass
#----------------------------------------------------------------------
def onSeek(self, event):
"""
Seeks the media file according to the amount the slider has
been adjusted.
"""
offset = self.playbackSlider.GetValue()
self.mediaPlayer.Seek(offset)
#----------------------------------------------------------------------
def onSetVolume(self, event):
"""
Sets the volume of the music player
"""
self.currentVolume = self.volumeCtrl.GetValue()
print "setting volume to: %s" % int(self.currentVolume)
self.mediaPlayer.SetVolume(self.currentVolume)
#----------------------------------------------------------------------
def onStop(self, event):
"""
Stops the music and resets the play button
"""
self.mediaPlayer.Stop()
self.playPauseBtn.SetToggle(False)
#----------------------------------------------------------------------
def onTimer(self, event):
"""
Keeps the player slider updated
"""
offset = self.mediaPlayer.Tell()
self.playbackSlider.SetValue(offset)
########################################################################
class MediaFrame(wx.Frame):
#----------------------------------------------------------------------
def __init__(self):
wx.Frame.__init__(self, None, wx.ID_ANY, "Python Music Player")
panel = MediaPanel(self)
#----------------------------------------------------------------------
# Run the program
if __name__ == "__main__":
app = wx.App(False)
frame = MediaFrame()
frame.Show()
app.MainLoop()
It may be that I didn't install wx correctly. I am using Python 2.4 and I was unable to find the wx module for Python 2.4. I downloaded wx for Python 2.5 and pasted the wx folder into the Python 2.4 directory. Can you please guide me how to add the wx module in Python 2.4?

Check here.
The 2.8.10 version still has binary installers for 2.4

Related

how to get a variable out of wxpython file open

I am trying to get a variable out of wxPython file open dialog. I have 2 button which gets the path to 2 files with .GetPath() ?
this is the code I have so far
'def onclk1(event):
with wx.FileDialog(panel, "OPEN EMG FILE", wildcard="TXT Files(*.txt)|*.txt",
style=wx.FD_OPEN | wx.FD_FILE_MUST_EXIST) as EmgFile:
if EmgFile.ShowModal() == wx.ID_CANCEL:
return "cancelled"
emg = EmgFile.GetPath()
e1.Bind(wx.EVT_BUTTON, onclk1)
Now I need to pass the path outside def to another variable.
Thanks in advance
In future it might be better to provide a minimal working example of your code.
Don't forget that a GUI is event driven and you must use the event to assign the return value of a dialog to the variable you want.
You've not said what you want to do with the file path, but this code shows how to assign it to a label.
"""Main Frame module for basic wxPython App."""
import wx
class MainFrame(wx.Frame):
"""Create MainFrame class."""
def __init__(self, *args, **kwargs):
super().__init__(None, *args, **kwargs)
self.size = (400, 1000)
self.Title = 'wx App'
self.Bind(wx.EVT_CLOSE, self.on_quit_click)
self.panel = MainPanel(self)
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(self.panel)
self.SetSizer(sizer)
self.Center()
self.Show()
def onclk1(self, event):
with wx.FileDialog(self.panel, "OPEN EMG FILE", wildcard="TXT Files(*.txt)|*.txt",
style=wx.FD_OPEN | wx.FD_FILE_MUST_EXIST) as EmgFile:
if EmgFile.ShowModal() == wx.ID_CANCEL:
return "cancelled"
emg = EmgFile.GetPath()
self.panel.lbl_file1.SetLabel(emg)
def on_quit_click(self, event):
"""Handle close event."""
del event
wx.CallAfter(self.Destroy)
class MainPanel(wx.Panel):
"""Create a panel class to contain screen widgets."""
def __init__(self, parent, *args, **kwargs):
super().__init__(parent, *args, **kwargs)
e1 = wx.Button(self, label='File1')
e1.Bind(wx.EVT_BUTTON, parent.onclk1)
self.lbl_file1 = wx.StaticText(self, label=' '*100)
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(e1)
sizer.Add(self.lbl_file1)
self.SetSizer(sizer)
if __name__ == '__main__':
wx_app = wx.App()
MainFrame()
wx_app.MainLoop()
Just to provide another option, there is also a wx.FilePickerCtrl
import wx
import os
wildcard = "All files (*.*)|*.*"
class MainWindow(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, title='File Selector')
self.currentDirectory = os.getcwd()
self.panel = wx.Panel(self)
vbox = wx.BoxSizer(wx.VERTICAL)
ie_box = wx.StaticBox(self.panel, -1, 'Please select the input file')
ie_sizer = wx.StaticBoxSizer(ie_box, wx.VERTICAL)
fl_box = wx.BoxSizer(wx.HORIZONTAL)
self.fl_ctrl = wx.FilePickerCtrl(self.panel, message="Choose a file")
fl_box.Add(self.fl_ctrl, 1, wx.ALL | wx.CENTER | wx.EXPAND, 5)
ie_sizer.Add(fl_box, 1, wx.ALL | wx.CENTER | wx.EXPAND, 10)
self.fl_ctrl.Bind(wx.EVT_FILEPICKER_CHANGED, self.on_open_file)
vbox.Add(ie_sizer, 0, wx.ALL | wx.CENTER | wx.EXPAND, 5)
self.panel.SetSizer(vbox)
self.Center()
self.panel.Fit()
self.Show()
def on_open_file(self, event):
self.fl_ctrl.GetPath()
if __name__ == '__main__':
app = wx.App()
frame = MainWindow()
app.MainLoop()

wx.Frame error when calling one script from another

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())

On button click open wxpython TextEntryDialog and get multiple input from user

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()

MplayerCtrl - MPlayer on Mac with WxPython

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.

Python WX - Returning user input from wx Dialog

I'm new to Python and WX. I created a simple test dialog shown below that prompts the user with a combobox. I would like to capture the value from the combox in my main program. How do I call it from my main program?
This is how I was purposing to call it that displays the dialog but does not currently capture the value from the combobox:
import highlight
highlight.create(self).Show(True)
a = highlight.OnComboBox1Combobox(self)
print a
The name of the Dialog file is "highlight". Below is the code:
#Boa:Dialog:Dialog2
import wx
def create(parent):
return Dialog2(parent)
[wxID_DIALOG2, wxID_DIALOG2COMBOBOX1, wxID_DIALOG2STATICTEXT1,
] = [wx.NewId() for _init_ctrls in range(3)]
class Dialog2(wx.Dialog):
def _init_ctrls(self, prnt):
# generated method, don't edit
wx.Dialog.__init__(self, id=wxID_DIALOG2, name='', parent=prnt,
pos=wx.Point(264, 140), size=wx.Size(400, 485),
style=wx.DEFAULT_DIALOG_STYLE, title='Dialog2')
self.SetClientSize(wx.Size(384, 447))
self.comboBox1 = wx.ComboBox(choices=['test1', 'test2'],
id=wxID_DIALOG2COMBOBOX1, name='comboBox1', parent=self,
pos=wx.Point(120, 16), size=wx.Size(130, 21), style=0,
value=u'wining\n')
self.comboBox1.SetToolTipString(u'comboBox1')
self.comboBox1.SetLabel(u'wining\n')
self.comboBox1.Bind(wx.EVT_COMBOBOX, self.OnComboBox1Combobox,
id=wxID_DIALOG2COMBOBOX1)
self.staticText1 = wx.StaticText(id=wxID_DIALOG2STATICTEXT1,
label=u'test', name='staticText1', parent=self, pos=wx.Point(88,
16), size=wx.Size(19, 13), style=0)
def __init__(self, parent):
self._init_ctrls(parent)
##print get_selection
##print get_selection1
def OnComboBox1Combobox(self, event):
get_selection = self.comboBox1.GetValue()
return get_selection
There are lots of dialog examples out there. Here are a couple:
The Dialogs of wxPython (Part 1 of 2)
http://zetcode.com/wxpython/dialogs/
Basically, all you need to do is instantiate your dialog, show it and then before you close it, extract the value. The typical way to do it is something like this:
myDlg = MyDialog()
res = myDlg.ShowModal()
if res == wx.ID_OK:
value = myDlg.myCombobox.GetValue()
myDlg.Destroy()
Update: Here's a more full-fledged example:
import wx
########################################################################
class MyDialog(wx.Dialog):
""""""
#----------------------------------------------------------------------
def __init__(self):
"""Constructor"""
wx.Dialog.__init__(self, None, title="Dialog")
self.comboBox1 = wx.ComboBox(self,
choices=['test1', 'test2'],
value="")
okBtn = wx.Button(self, wx.ID_OK)
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(self.comboBox1, 0, wx.ALL|wx.CENTER, 5)
sizer.Add(okBtn, 0, wx.ALL|wx.CENTER, 5)
self.SetSizer(sizer)
########################################################################
class MainProgram(wx.Frame):
""""""
#----------------------------------------------------------------------
def __init__(self):
"""Constructor"""
wx.Frame.__init__(self, None, title="Main Program")
panel = wx.Panel(self)
btn = wx.Button(panel, label="Open dialog")
btn.Bind(wx.EVT_BUTTON, self.onDialog)
self.Show()
#----------------------------------------------------------------------
def onDialog(self, event):
""""""
dlg = MyDialog()
res = dlg.ShowModal()
if res == wx.ID_OK:
print dlg.comboBox1.GetValue()
dlg.Destroy()
if __name__ == "__main__":
app = wx.App(False)
frame = MainProgram()
app.MainLoop()

Categories