Global name 'img' is not defined? - python

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.

Related

add file dialog to Menu Functionality (open ) wxpython 3

i use wxpython for python3
i try to creat my simple application and i 'm try to create the menu and with 2 panels
i need to add a file dialog when the user click in the button OPEN in the menu to chose the file , i don't know how can add it in my code
this is my code :
import wx
class MainFrame(wx.Frame):
def __init__(self, *args, **kwargs):
super(MainFrame, self).__init__(None, *args, **kwargs)
self.Title = 'premier app (Menu+2windows)'
self.SetMenuBar(MenuBar(self))
self.ToolBar = MainToolbar(self)
self.status_bar = StatusBar(self).status_bar
self.Bind(wx.EVT_CLOSE, self.on_quit_click)
panel = MainPanel(self)
sizer = wx.BoxSizer()
sizer.Add(panel)
self.SetSizerAndFit(sizer)
self.Centre()
self.Show()
def on_quit_click(self, event):
del event
wx.CallAfter(self.Destroy)
class MainPanel(wx.Panel):
def __init__(self, parent):
wx.Frame.__init__(self, parent,size = (500,500))
self.splitter = wx.SplitterWindow(self, -1, size = (500,500))
# 1er panel
pan1 = wx.Window(self.splitter, style=wx.BORDER_SUNKEN)
pan1.SetBackgroundColour("yellow")
wx.StaticText(pan1, -1)
#2em panel
pan2 = wx.Window(self.splitter, style=wx.BORDER_SUNKEN)
pan2.SetBackgroundColour("blue")
wx.StaticText(pan2, -1)
self.splitter.SplitVertically(pan1, pan2, 100)
class MenuBar(wx.MenuBar):
"""creation de menu."""
def __init__(self, parent, *args, **kwargs):
super(MenuBar, self).__init__(*args, **kwargs)
# menu
File_menu = wx.Menu()
Edit_menu = wx.Menu()
Help_menu = wx.Menu()
self.Append(File_menu, '&File')
self.Append(Edit_menu, '&Edit')
self.Append( Help_menu, '&Help')
quit_menu_item = wx.MenuItem(File_menu, wx.ID_EXIT)
parent.Bind(wx.EVT_MENU, parent.on_quit_click, id=wx.ID_EXIT)
open_menu_item = wx.MenuItem(File_menu, wx.ID_OPEN)
new_menu_item = wx.MenuItem(File_menu,wx.ID_NEW)
File_menu.Append(open_menu_item)
File_menu.Append(new_menu_item)
File_menu.Append(quit_menu_item)
class MainToolbar(wx.ToolBar):
"""creation toolbar."""
def __init__(self, parent, *args, **kwargs):
super(MainToolbar, self).__init__(parent, *args, **kwargs)
class StatusBar(object):
def __init__(self, parent):
self.status_bar = parent.CreateStatusBar()
if __name__ == '__main__':
"""Run the application."""
screen_app = wx.App()
main_frame = MainFrame()
screen_app.MainLoop()
need some help
thank u
With this code:
quit_menu_item = wx.MenuItem(File_menu, wx.ID_EXIT)
parent.Bind(wx.EVT_MENU, parent.on_quit_click, id=wx.ID_EXIT)
you are binding the Quit menu item to a Quit function.
Do the same for the Open function i.e. Bind it to something like parent.on_open_file
In that function, do something like this.
def self.on_open_file(self, event):
dlg = wx.FileDialog(self, message="Choose file", defaultDir = "/home", defaultFile = "",\
wildcard = "", style=wx.FD_OPEN)
if dlg.ShowModal() == wx.ID_OK:
print(dlg.GetDirectory(), dlg.GetFilename())
dlg.Destroy()

wxPython : Adding an about box.

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

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.

wxpython add folder to listctrl?

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)

How to restore a minimized Window/Frame in wxpython/python

I have 2 frames in a python script. Once the first one gets minimized, the second one shows. How do I get the original one to go from being minimized to restored after I close the second one.
Here is my code so far:
import wx
import wx.media
import os
class MainWindow(wx.Frame):
def __init__(self,parent,id):
wx.Frame.__init__(self,parent,id,'Music Player',size=(900,600), style=wx.MINIMIZE_BOX|wx.SYSTEM_MENU|wx.CAPTION|wx.CLOSE_BOX|wx.CLIP_CHILDREN)
wx.Frame.CenterOnScreen(self)
panel=wx.Panel(self)
panel2=wx.Panel(panel,-1, (0,0), (160,600))
##wx.Frame.Maximize(self)
panel.SetBackgroundColour('grey')
panel2.SetBackgroundColour('black')
##MENU AND STATUS BAR
status=self.CreateStatusBar()
menubar=wx.MenuBar()
file_menu=wx.Menu()
help_menu=wx.Menu()
ID_FILE_NEW = 1
ID_FILE_LOAD = 2
ID_FILE_EXIT = 3
file_menu.Append(ID_FILE_NEW,"New Window","This will open a new window")
file_menu.Append(ID_FILE_LOAD,"Load...", "This will let you choose a song to load")
file_menu.Append(ID_FILE_EXIT,"Exit","This will exit the program")
menubar.Append(file_menu,"File")
self.SetMenuBar(menubar)
self.Bind(wx.EVT_MENU, self.newWin, None, 1)
self.Bind(wx.EVT_MENU, self.Load, None, 2)
self.Bind(wx.EVT_MENU, self.Close, None, 3)
## heading = wx.StaticText(panel, -1, "Music Player",pos=(345,10))
font1 = wx.Font(14, wx.DEFAULT, wx.NORMAL, wx.BOLD)
font2 = wx.Font(14, wx.DEFAULT, wx.NORMAL, wx.BOLD)
## heading.SetFont(font1)
try:
self.mc = wx.media.MediaCtrl(self)
except NotImplementedError:
raise
loadButton = wx.Button(panel2, -1, "Load File", pos=(30,10))
self.Bind(wx.EVT_BUTTON, self.Load, loadButton)
playButton = wx.Button(panel2, -1, "Play", pos=(30,50))
self.Bind(wx.EVT_BUTTON, self.Play, playButton)
pauseButton = wx.Button(panel2, -1, "Pause", pos=(30,90))
self.Bind(wx.EVT_BUTTON, self.Pause, pauseButton)
stopButton = wx.Button(panel2, -1, "Stop", pos=(30,130))
self.Bind(wx.EVT_BUTTON, self.Stop, stopButton)
self.playbackSlider = wx.Slider(panel, size=(400,45), pos=(310,50))
self.playbackSlider.SetRange(0,self.mc.Length())
self.Bind(wx.EVT_SLIDER, self.onSeek, self.playbackSlider)
self.playbackSlider.SetBackgroundColour('grey')
self.volumeCtrl = wx.Slider(panel, value=50, minValue=0, maxValue=100, style=wx.SL_VERTICAL|wx.SL_INVERSE, pos=(180,40))
self.volumeCtrl.Bind(wx.EVT_SLIDER, self.onSetVolume)
self.timer = wx.Timer(self)
self.Bind(wx.EVT_TIMER, self.onTimer)
self.timer.Start(100)
self.Bind(wx.EVT_ICONIZE, self.newWin2)
self.st_file = wx.StaticText(self, -1, "**Nothing** Please click the \"Load File\" Button", pos=(310,10))
playing = wx.StaticText(self, -1, "Now Playing: ", pos=(165,10))
playing.SetFont(font2)
self.st_file.SetFont(font1)
playing.SetBackgroundColour('grey')
self.st_file.SetBackgroundColour('grey')
playing.SetForegroundColour('white')
self.st_file.SetForegroundColour('white')
def newWin2(self, event):
if self.IsIconized() == True:
self.new = NewWindow(parent=None, id=-1)
self.new.Show()
def newWin(self, event):
self.new = NewWindow(parent=None, id=-1)
self.new.Show()
def Close(self, event):
box=wx.MessageDialog(None, 'Are you sure you want to exit?', 'Exit program?', wx.YES_NO)
answer=box.ShowModal()
if answer==wx.ID_YES:
self.Destroy()
def Load(self, event):
dlg = wx.FileDialog(self, "Choose a media file", "songs", "", "*.*", wx.OPEN)
if dlg.ShowModal() == wx.ID_OK:
path = dlg.GetPath()
self.doLoadFile(path)
dlg.Destroy()
def doLoadFile(self, path):
if not self.mc.Load(path):
wx.MessageBox("Unable to load %s: Unsupported format?" % path, "ERROR", wx.ICON_ERROR | wx.OK)
else:
folder, filename = os.path.split(path)
self.st_file.SetLabel('%s' % filename)
self.mc.SetBestFittingSize()
self.mc.Play()
def Play(self, event):
self.mc.Play()
self.playbackSlider.SetRange(0,self.mc.Length())
def Pause(self, event):
self.mc.Pause()
def Stop(self, event):
self.mc.Stop()
def onSetVolume(self, event):
self.currentVolume = self.volumeCtrl.GetValue()
self.mc.SetVolume(float(self.currentVolume) / 100)
def onTimer(self, event):
offset = self.mc.Tell()
self.playbackSlider.SetValue(offset)
def onSeek(self, event):
offset = self.playbackSlider.GetValue()
self.mc.Seek(offset)
class NewWindow(wx.Frame):
def __init__(self,parent,id):
wx.Frame.__init__(self, parent, id, 'New Window', size=(130,150), pos=(0,0), style=wx.MINIMIZE_BOX|wx.CLOSE_BOX)
self.SetBackgroundColour('grey')
playButton = wx.Button(self, -1, "Play", pos=(5,10))
self.Bind(wx.EVT_BUTTON, self.Play, playButton)
pauseButton = wx.Button(self, -1, "Pause", pos=(5,40))
self.Bind(wx.EVT_BUTTON, self.Pause, pauseButton)
stopButton = wx.Button(self, -1, "Stop", pos=(5,70))
self.Bind(wx.EVT_BUTTON, self.Stop, stopButton)
closeButton = wx.Button(self, -1, "Close", pos=(5,120))
self.Bind(wx.EVT_BUTTON, self.Close, closeButton)
def Play(self, event):
self.mc.Play()
self.playbackSlider.SetRange(0,self.mc.Length())
def Pause(self, event):
self.mc.Pause()
def Stop(self, event):
self.mc.Stop()
def onSetVolume(self, event):
self.currentVolume = self.volumeCtrl.GetValue()
self.mc.SetVolume(float(self.currentVolume) / 100)
def Close(self, event):
self.Destroy()
################## I WANT TO ADD WHATEVER I NEED TO HERE TO RESTORE THE MINIMIZED FRAME AFTER THE CLOSE BUTTON IS PRESSED.
##RUN##
if __name__=='__main__':
app=wx.PySimpleApp()
frame=MainWindow(parent=None,id=-1)
frame.Show()
app.MainLoop()
the_app.SetTopWindow(wxFrameObject)
wxFrameObject.Maximize()
might work ... thats what we use
You should use myFrameObject.Raise() to make it come out of its minimized state. The wx.STAY_ON_TOP flag is for making the frame stay on top of all other frames when it's not minimized, but it won't do anything if you have minimized the frame.

Categories