Search Results

Search found 21 results on 1 pages for 'filedialog'.

Page 1/1 | 1 

  • SWT Filedialog Open into home folder

    - by Ivan
    I want to open a FileDialog window into the user home folder (i.e. /home/user or /Users/unsername) I read the user home folder, using System.getProperty: String homefolder = System.getProperty(user.home); And the variable containts the correct home folder. But when i set the filterpath in FileDialog, it opens (in linux) only the /home level not entering into the user home dir. This is the source code: FileDialog dialog = new FileDialog(shell); dialog.setText("Choose a certificate"); String platform = SWT.getPlatform(); String homefolder = System.getProperty("user.home"); dialog.setFilterPath(homefolder); Any idea? Here a screenshot:

    Read the article

  • FileDialog DoubleClick Behavior

    - by Shaun Hamman
    While developing a WinForms application, I came across what I believe is a bug in the OpenFileDialog and SaveFileDialog controls. A Google search turned up a single other person who noticed the same issue, but neither a solution nor a workaround was provided. You can view this thread at: http://bytes.com/topic/visual-basic-net/answers/389470-open-file-dialog-picturebox-click-event. I have a custom control on my form that handles the MouseDown event. If I doubleclick a file in a FileDialog control while the mouse is over this control (with the dialog between them, obviously), the MouseDown event gets triggered. I don't think this is an issue with my control, because the person I mentioned before noticed this happening with a PictureBox control. It would seem that even though the mouse button was pressed down (for the second click to open the file) while on the dialog box, the event passed through to the form and my control when the dialog closed. I have tried disabling my control while the dialog box is active, but that didn't stop it from capturing the event. I assume this is because the event is passed down after the dialog closes, so my control would be re-enabled. Does anyone know of a way to prevent that click from reaching the form and, in turn, my control? Also, can anyone confirm if this really is a bug in the FileDialog controls, or if I just have some setting configured incorrectly?

    Read the article

  • wxPython: Change a buttons text in a wx.FileDialog

    - by Sascha
    Hello I have a wx.FileDialog (with the wx.FD_OPEN flag) & I would like to know if I can (& how) I could change the button in the bottom right of the FileDialog from "Open" to "Create" or "Delete", etc. What I am doing is I have a button with the text "Delete Portfolio", when pressed it opens a FileDialog & allows the user to select a portfolio file(.db) to delete. So instead of the File Dialog's bottom right confirm button displaying "Open" I would like to be able to change the text to "Confirm" or "Delete" or whatever. Is this possible, its a rather superficial thing to do, but if the button says open when the user wants to select a file to delete, it can be a little confusing even if the title of the dialog says "please select a file to delete"

    Read the article

  • Where is Outlook's save FileDialog?

    - by matthews
    I'm working on an Outlook add-in that requires the Office specific FileDialog to interoperate with a Sharepoint site; the common file dialog doesn't have the interoperability. I know that both Word and Excel have a get_fileDialog method under Globals.ThisAddIn.Application.Application, but Outlook doesn't seem to. How do I launch an Outlook FileDialog? Is it even possible?

    Read the article

  • Making File Dialog only accept directories

    - by matt
    I want to have a file dialog only allow directories, here's what I've been trying: fileDialog = QtGui.QFileDialog() fileDialog.setFileMode(QtGui.QFileDialog.ShowDirsOnly) filename = fileDialog.getOpenFileName(self, 'Select USB Drive Location')) Thank You

    Read the article

  • Win7: Deadlock on filedialog

    - by Fuxi
    i'm having a very strange problem: i'm running win7 64bit on my laptop - i hooked an external HD via usb3. when saving something in certain applications (eg. notepad), the file dialog pops up then the whole system is freezing .. like applications won't react anymore, also taskmanager, so i can't terminate anything. i think it's the external HD which is powering down after a while. anyone who knows this problem and can tell me how to fix it? thanks

    Read the article

  • Java FileDialog programmatically set size

    - by rwallace
    I want to display a Java FileDialog and sets its initial size to something reasonable (it doesn't show the maximize button, and a lot of users might not know you can use alt-space X instead). I tried setBounds but it didn't do anything, and I don't see a method for maximizing it; what am I missing? Update: on Windows at least, the system file dialog remembers size and maximize state even across program invocations, so the user can set it to the desired size just once and it will stay that way; that seems sufficient, so I will leave it at that.

    Read the article

  • Swt file dialog too much files selected?

    - by InsertNickHere
    Hi there, the swt file dialog will give me an empty result array if I select too much files (approx. 2500files). The listing shows you how I use this dialog. If i select too many sound files, the syso will show 0. Debugging tells me, that the files array is empty in this case. Is there any way to get this work? FileDialog fileDialog = new FileDialog(mainView.getShell(), SWT.MULTI); fileDialog.setText("Choose sound files"); fileDialog.setFilterExtensions(new String[] { new String("*.wav") }); Vector<String> result = new Vector<String>(); fileDialog.open(); String[] files = fileDialog.getFileNames(); for (int i = 0, n = files.length; i < n; i++) { if( !files[i].contains(".wav")) { System.out.println(files[i]); } StringBuffer stringBuffer = new StringBuffer(); stringBuffer.append(fileDialog.getFilterPath()); if (stringBuffer.charAt(stringBuffer.length() - 1) != File.separatorChar) { stringBuffer.append(File.separatorChar); } stringBuffer.append(files[i]); stringBuffer.append(""); String finalName = stringBuffer.toString(); if( !finalName.contains(".wav")) { System.out.println(finalName); } result.add(finalName); } System.out.println(result.size()) ;

    Read the article

  • Subclassing a window from a thread in c#

    - by user258651
    I'm creating a thread that looks for a window. When it finds the window, it overrides its windowproc, and handles WM_COMMAND and WM_CLOSE. Here's the code that looks for the window and subclasses it: public void DetectFileDialogProc() { Window fileDialog = null; // try to find the dialog twice, with a delay of 500 ms each time for (int attempts = 0; fileDialog == null && attempts < 2; attempts++) { // FindDialogs enumerates all windows of class #32770 via an EnumWindowProc foreach (Window wnd in FindDialogs(500)) { IntPtr parent = NativeMethods.User32.GetParent(wnd.Handle); if (parent != IntPtr.Zero) { // we're looking for a dialog whose parent is a dialog as well Window parentWindow = new Window(parent); if (parentWindow.ClassName == NativeMethods.SystemWindowClasses.Dialog) { fileDialog = wnd; break; } } } } // if we found the dialog if (fileDialog != null) { OldWinProc = NativeMethods.User32.GetWindowLong(fileDialog.Handle, NativeMethods.GWL_WNDPROC); NativeMethods.User32.SetWindowLong(fileDialog.Handle, NativeMethods.GWL_WNDPROC, Marshal.GetFunctionPointerForDelegate(new WindowProc(WndProc)).ToInt32()); } } And the windowproc: public IntPtr WndProc(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam) { lock (this) { if (!handled) { if (msg == NativeMethods.WM_COMMAND || msg == NativeMethods.WM_CLOSE) { // adding to a list. i never access the window via the hwnd from this list, i just treat it as a number _addDescriptor(hWnd); handled = true; } } } return NativeMethods.User32.CallWindowProc(OldWinProc, hWnd, msg, wParam, lParam); } This all works well under normal conditions. But I am seeing two instances of bad behavior in order of badness: If I do not close the dialog within a minute or so, the app crashes. Is this because the thread is getting garbage collected? This would kind of make sense, as far as GC can tell the thread is done? If this is the case, (and I don't know that it is), how can I make the thread stay around as long as the dialog is around? If I immediately close the dialog with the 'X' button (WM_CLOSE) the app crashes. I believe its crashing in the windowproc, but I can't get a breakpoint in there. I'm getting an AccessViolationException, The exception says "Attempted to read or write protected memory. This is often an indication that other memory is corrupt." Its a race condition, but of what I don't know. FYI, I had been reseting the old windowproc once I processed the commands, but that was crashing even more often! Any ideas on how I can solve these issues?

    Read the article

  • add a from to backup routine

    - by Gerard Flynn
    hi how do you put a process bar and button onto this code i have class and want to add a gui on to the code using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Data.SqlClient; using System.IO; using System.Threading; using Tamir.SharpSsh; using System.Security.Cryptography; using ICSharpCode.SharpZipLib.Checksums; using ICSharpCode.SharpZipLib.Zip; using ICSharpCode.SharpZipLib.GZip; namespace backup { public partial class Form1 : Form { public Form1() { InitializeComponent(); } /// <summary> /// Summary description for Class1. /// </summary> public class Backup { private string dbName; private string dbUsername; private string dbPassword; private static string baseDir; private string backupName; private static bool isBackup; private string keyString; private string ivString; private string[] backupDirs = new string[0]; private string[] excludeDirs = new string[0]; private ZipOutputStream zipOutputStream; private string backupFile; private string zipFile; private string encryptedFile; static void Main() { Backup.Log("BackupUtility loaded"); try { new Backup(); if (!isBackup) MessageBox.Show("Restore complete"); } catch (Exception e) { Backup.Log(e.ToString()); if (!isBackup) MessageBox.Show("Error restoring!\r\n" + e.Message); } } private void LoadAppSettings() { this.backupName = System.Configuration.ConfigurationSettings.AppSettings["BackupName"].ToString(); this.dbName = System.Configuration.ConfigurationSettings.AppSettings["DBName"].ToString(); this.dbUsername = System.Configuration.ConfigurationSettings.AppSettings["DBUsername"].ToString(); this.dbPassword = System.Configuration.ConfigurationSettings.AppSettings["DBPassword"].ToString(); //default to using where we are executing this assembly from Backup.baseDir = System.Reflection.Assembly.GetExecutingAssembly().Location.Substring(0, System.Reflection.Assembly.GetExecutingAssembly().Location.LastIndexOf("\\")) + "\\"; Backup.isBackup = bool.Parse(System.Configuration.ConfigurationSettings.AppSettings["IsBackup"].ToString()); this.keyString = System.Configuration.ConfigurationSettings.AppSettings["KeyString"].ToString(); this.ivString = System.Configuration.ConfigurationSettings.AppSettings["IVString"].ToString(); this.backupDirs = GetSetting("BackupDirs", ','); this.excludeDirs = GetSetting("ExcludeDirs", ','); } private string[] GetSetting(string settingName, char delimiter) { if (System.Configuration.ConfigurationSettings.AppSettings[settingName] != null) { string settingVal = System.Configuration.ConfigurationSettings.AppSettings[settingName].ToString(); if (settingVal.Length > 0) return settingVal.Split(delimiter); } return new string[0]; } public Backup() { this.LoadAppSettings(); if (isBackup) this.DoBackup(); else this.DoRestore(); Log("Finished"); } private void DoRestore() { System.Windows.Forms.OpenFileDialog fileDialog = new System.Windows.Forms.OpenFileDialog(); fileDialog.Title = "Choose .encrypted file"; fileDialog.Filter = "Encrypted files (*.encrypted)|*.encrypted|All files (*.*)|*.*"; fileDialog.InitialDirectory = Backup.baseDir; if (fileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK) { //string encryptedFile = GetFileName("encrypted"); string encryptedFile = fileDialog.FileName; string decryptedFile = this.GetDecryptedFilename(encryptedFile); //string originalFile = GetFileName("original"); this.Decrypt(encryptedFile, decryptedFile); //this.UnzipFile(decryptedFile, originalFile); } } //use the same filename as the backup except replace ".encrypted" with ".decrypted.zip" private string GetDecryptedFilename(string encryptedFile) { string name = encryptedFile.Substring(0, encryptedFile.LastIndexOf(".")); name += ".decrypted.zip"; return name; } private void DoBackup() { this.backupFile = GetFileName("bak"); this.zipFile = GetFileName("zip"); this.encryptedFile = GetFileName("encrypted"); this.DeleteFiles(); this.zipOutputStream = new ZipOutputStream(File.Create(zipFile)); try { //backup database first if (this.dbName.Length > 0) { this.BackupDB(backupFile); this.ZipFile(backupFile, this.GetName(backupFile)); } //zip any directories specified in config file this.ZipUserSpecifiedFilesAndDirectories(this.backupDirs); } finally { this.zipOutputStream.Finish(); this.zipOutputStream.Close(); } this.Encrypt(zipFile, encryptedFile); this.SCPFile(encryptedFile); this.DeleteFiles(); } /// <summary> /// Deletes any files created by the backup process, namely the DB backup file, /// the zip of all files backuped up, and the encrypred zip file /// </summary> private void DeleteFiles() { File.Delete(this.backupFile); File.Delete(this.zipFile); ///File.Delete(this.encryptedFile); } private void ZipUserSpecifiedFilesAndDirectories(string[] fileNames) { foreach (string fileName in fileNames) { string name = fileName.Trim(); if (name.Length > 0) { Log("Zipping " + name); this.ZipFile(name, this.GetNameFromDir(name)); } } } private void SCPFile(string inputPath) { string sshServer = System.Configuration.ConfigurationSettings.AppSettings["SSHServer"].ToString(); string sshUsername = System.Configuration.ConfigurationSettings.AppSettings["SSHUsername"].ToString(); string sshPassword = System.Configuration.ConfigurationSettings.AppSettings["SSHPassword"].ToString(); if (sshServer.Length > 0 && sshUsername.Length > 0 && sshPassword.Length > 0) { Scp scp = new Scp(sshServer, sshUsername, sshPassword); //Copy a file from local machine to remote SSH server scp.Connect(); Log("Connected to " + sshServer); //scp.Put(inputPath, "/home/wal/temp.txt"); scp.Put(inputPath, GetName(inputPath)); scp.Close(); } else { Log("Not SCP as missing login details"); } } private string GetName(string inputPath) { FileInfo info = new FileInfo(inputPath); return info.Name; } private string GetNameFromDir(string inputPath) { DirectoryInfo info = new DirectoryInfo(inputPath); return info.Name; } private static void Log(string msg) { try { string toLog = DateTime.Now.ToString() + ": " + msg; System.Diagnostics.Debug.WriteLine(toLog); System.IO.FileStream fs = new System.IO.FileStream(baseDir + "app.log", System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite); System.IO.StreamWriter m_streamWriter = new System.IO.StreamWriter(fs); m_streamWriter.BaseStream.Seek(0, System.IO.SeekOrigin.End); m_streamWriter.WriteLine(toLog); m_streamWriter.Flush(); m_streamWriter.Close(); fs.Close(); } catch (Exception e) { Console.WriteLine(e.ToString()); } } private byte[] GetFileBytes(string path) { FileStream stream = new FileStream(path, FileMode.Open); byte[] bytes = new byte[stream.Length]; stream.Read(bytes, 0, bytes.Length); stream.Close(); return bytes; } private void WriteFileBytes(byte[] bytes, string path) { FileStream stream = new FileStream(path, FileMode.Create); stream.Write(bytes, 0, bytes.Length); stream.Close(); } private void UnzipFile(string inputPath, string outputPath) { ZipInputStream zis = new ZipInputStream(File.OpenRead(inputPath)); ZipEntry theEntry = zis.GetNextEntry(); FileStream streamWriter = File.Create(outputPath); int size = 2048; byte[] data = new byte[2048]; while (true) { size = zis.Read(data, 0, data.Length); if (size > 0) { streamWriter.Write(data, 0, size); } else { break; } } streamWriter.Close(); zis.Close(); } private bool ExcludeDir(string dirName) { foreach (string excludeDir in this.excludeDirs) { if (dirName == excludeDir) return true; } return false; } private void ZipFile(string inputPath, string zipName) { FileAttributes fa = File.GetAttributes(inputPath); if ((fa & FileAttributes.Directory) != 0) { string dirName = zipName + "/"; ZipEntry entry1 = new ZipEntry(dirName); this.zipOutputStream.PutNextEntry(entry1); string[] subDirs = Directory.GetDirectories(inputPath); //create directories first foreach (string subDir in subDirs) { DirectoryInfo info = new DirectoryInfo(subDir); string name = info.Name; if (this.ExcludeDir(name)) Log("Excluding " + dirName + name); else this.ZipFile(subDir, dirName + name); } //then store files string[] fileNames = Directory.GetFiles(inputPath); foreach (string fileName in fileNames) { FileInfo info = new FileInfo(fileName); string name = info.Name; this.ZipFile(fileName, dirName + name); } } else { Crc32 crc = new Crc32(); this.zipOutputStream.SetLevel(6); // 0 - store only to 9 - means best compression FileStream fs = null; try { fs = File.OpenRead(inputPath); } catch (IOException ioEx) { Log("WARNING! " + ioEx.Message);//might be in use, skip file in this case } if (fs != null) { byte[] buffer = new byte[fs.Length]; fs.Read(buffer, 0, buffer.Length); ZipEntry entry = new ZipEntry(zipName); entry.DateTime = DateTime.Now; // set Size and the crc, because the information // about the size and crc should be stored in the header // if it is not set it is automatically written in the footer. // (in this case size == crc == -1 in the header) // Some ZIP programs have problems with zip files that don't store // the size and crc in the header. entry.Size = fs.Length; fs.Close(); crc.Reset(); crc.Update(buffer); entry.Crc = crc.Value; this.zipOutputStream.PutNextEntry(entry); this.zipOutputStream.Write(buffer, 0, buffer.Length); } } } private void Encrypt(string inputPath, string outputPath) { RijndaelManaged rijndaelManaged = new RijndaelManaged(); byte[] encrypted; byte[] toEncrypt; //Create a new key and initialization vector. //myRijndael.GenerateKey(); //myRijndael.GenerateIV(); /*des.GenerateKey(); des.GenerateIV(); string temp1 = Convert.ToBase64String(des.Key); string temp2 = Convert.ToBase64String(des.IV);*/ //Get the key and IV. byte[] key = Convert.FromBase64String(keyString); byte[] IV = Convert.FromBase64String(ivString); //Get an encryptor. ICryptoTransform encryptor = rijndaelManaged.CreateEncryptor(key, IV); //Encrypt the data. MemoryStream msEncrypt = new MemoryStream(); CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write); //Convert the data to a byte array. toEncrypt = this.GetFileBytes(inputPath); //Write all data to the crypto stream and flush it. csEncrypt.Write(toEncrypt, 0, toEncrypt.Length); csEncrypt.FlushFinalBlock(); //Get encrypted array of bytes. encrypted = msEncrypt.ToArray(); WriteFileBytes(encrypted, outputPath); } private void Decrypt(string inputPath, string outputPath) { RijndaelManaged myRijndael = new RijndaelManaged(); //DES des = new DESCryptoServiceProvider(); byte[] key = Convert.FromBase64String(keyString); byte[] IV = Convert.FromBase64String(ivString); byte[] encrypted = this.GetFileBytes(inputPath); byte[] fromEncrypt; //Get a decryptor that uses the same key and IV as the encryptor. ICryptoTransform decryptor = myRijndael.CreateDecryptor(key, IV); //Now decrypt the previously encrypted message using the decryptor // obtained in the above step. MemoryStream msDecrypt = new MemoryStream(encrypted); CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read); fromEncrypt = new byte[encrypted.Length]; //Read the data out of the crypto stream. int bytesRead = csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length); byte[] readBytes = new byte[bytesRead]; Array.Copy(fromEncrypt, 0, readBytes, 0, bytesRead); this.WriteFileBytes(readBytes, outputPath); } private string GetFileName(string extension) { return baseDir + backupName + "_" + DateTime.Now.ToString("yyyyMMdd") + "." + extension; } private void BackupDB(string backupPath) { string sql = @"DECLARE @Date VARCHAR(300), @Dir VARCHAR(4000) --Get today date SET @Date = CONVERT(VARCHAR, GETDATE(), 112) --Set the directory where the back up file is stored SET @Dir = '"; sql += backupPath; sql += @"' --create a 'device' to write to first EXEC sp_addumpdevice 'disk', 'temp_device', @Dir --now do the backup BACKUP DATABASE " + this.dbName; sql += @" TO temp_device WITH FORMAT --Drop the device EXEC sp_dropdevice 'temp_device' "; //Console.WriteLine("sql="+sql); Backup.Log("Starting backup of " + this.dbName); ExecuteSQL(sql); } /// <summary> /// Executes the specified SQL /// Returns true if no errors were encountered during execution /// </summary> /// <param name="procedureName"></param> private void ExecuteSQL(string sql) { SqlConnection conn = new SqlConnection(this.GetDBConnectString()); try { SqlCommand comm = new SqlCommand(sql, conn); conn.Open(); comm.ExecuteNonQuery(); } finally { conn.Close(); } } private string GetDBConnectString() { StringBuilder builder = new StringBuilder(); builder.Append("Data Source=127.0.0.1; User ID="); builder.Append(this.dbUsername); builder.Append("; Password="); builder.Append(this.dbPassword); builder.Append("; Initial Catalog="); builder.Append(this.dbName); builder.Append(";Connect Timeout=30"); return builder.ToString(); } } } }

    Read the article

  • Access 2007 file picker, replaces all rows with the same choice.

    - by SqlStruggle
    This code is from an Access 2007 project I've been struggling with. The actual mean part is the part where I should put something like "update only current form" DoCmd.RunSQL "Update Korut Set [PikkuKuva]=('" & varFile & "') ;" Could someone please help me with this?` If I use it now, it updates all the tables with the same file picked. Heres the whole code. ' This requires a reference to the Microsoft Office 11.0 Object Library. Dim fDialog As Office.FileDialog Dim varFile As Variant Dim filePath As String ' Set up the File dialog box. Set fDialog = Application.FileDialog(msoFileDialogFilePicker) With fDialog ' Allow the user to make multiple selections in the dialog box. .AllowMultiSelect = False ' Set the title of the dialog box. .Title = "Valitse Tiedosto" ' Clear out the current filters, and then add your own. .Filters.Clear .Filters.Add "All Files", "*.*" ' user picked at least one file. If the .Show method returns ' False, the user clicked Cancel. If .Show = True Then ' Loop through each file that is selected and then add it to the list box. For Each varFile In .SelectedItems DoCmd.SetWarnings True DoCmd.RunSQL "Update Korut Set [PikkuKuva]=('" & varFile & "') ;" Next Else MsgBox "You clicked Cancel in the file dialog box." End If End With

    Read the article

  • Yes, another thread question...

    - by Michael
    I can't understand why I am loosing control of my GUI even though I am implementing a thread to play a .wav file. Can someone pin point what is incorrect? #!/usr/bin/env python import wx, pyaudio, wave, easygui, thread, time, os, sys, traceback, threading import wx.lib.delayedresult as inbg isPaused = False isStopped = False class Frame(wx.Frame): def __init__(self): print 'Frame' wx.Frame.__init__(self, parent=None, id=-1, title="Jasmine", size=(720, 300)) #initialize panel panel = wx.Panel(self, -1) #initialize grid bag sizer = wx.GridBagSizer(hgap=20, vgap=20) #initialize buttons exitButton = wx.Button(panel, wx.ID_ANY, "Exit") pauseButton = wx.Button(panel, wx.ID_ANY, 'Pause') prevButton = wx.Button(panel, wx.ID_ANY, 'Prev') nextButton = wx.Button(panel, wx.ID_ANY, 'Next') stopButton = wx.Button(panel, wx.ID_ANY, 'Stop') #add widgets to sizer sizer.Add(pauseButton, pos=(1,10)) sizer.Add(prevButton, pos=(1,11)) sizer.Add(nextButton, pos=(1,12)) sizer.Add(stopButton, pos=(1,13)) sizer.Add(exitButton, pos=(5,13)) #initialize song time gauge #timeGauge = wx.Gauge(panel, 20) #sizer.Add(timeGauge, pos=(3,10), span=(0, 0)) #initialize menuFile widget menuFile = wx.Menu() menuFile.Append(0, "L&oad") menuFile.Append(1, "E&xit") menuBar = wx.MenuBar() menuBar.Append(menuFile, "&File") menuAbout = wx.Menu() menuAbout.Append(2, "A&bout...") menuAbout.AppendSeparator() menuBar.Append(menuAbout, "Help") self.SetMenuBar(menuBar) self.CreateStatusBar() self.SetStatusText("Welcome to Jasime!") #place sizer on panel panel.SetSizer(sizer) #initialize icon self.cd_image = wx.Image('cd_icon.png', wx.BITMAP_TYPE_PNG) self.temp = self.cd_image.ConvertToBitmap() self.size = self.temp.GetWidth(), self.temp.GetHeight() wx.StaticBitmap(parent=panel, bitmap=self.temp) #set binding self.Bind(wx.EVT_BUTTON, self.OnQuit, id=exitButton.GetId()) self.Bind(wx.EVT_BUTTON, self.pause, id=pauseButton.GetId()) self.Bind(wx.EVT_BUTTON, self.stop, id=stopButton.GetId()) self.Bind(wx.EVT_MENU, self.loadFile, id=0) self.Bind(wx.EVT_MENU, self.OnQuit, id=1) self.Bind(wx.EVT_MENU, self.OnAbout, id=2) #Load file usiing FileDialog, and create a thread for user control while running the file def loadFile(self, event): foo = wx.FileDialog(self, message="Open a .wav file...", defaultDir=os.getcwd(), defaultFile="", style=wx.FD_MULTIPLE) foo.ShowModal() self.queue = foo.GetPaths() self.threadID = 1 while len(self.queue) != 0: self.song = myThread(self.threadID, self.queue[0]) self.song.start() while self.song.isAlive(): time.sleep(2) self.queue.pop(0) self.threadID += 1 def OnQuit(self, event): self.Close() def OnAbout(self, event): wx.MessageBox("This is a great cup of tea.", "About Jasmine", wx.OK | wx.ICON_INFORMATION, self) def pause(self, event): global isPaused isPaused = not isPaused def stop(self, event): global isStopped isStopped = not isStopped class myThread (threading.Thread): def __init__(self, threadID, wf): self.threadID = threadID self.wf = wf threading.Thread.__init__(self) def run(self): global isPaused global isStopped self.waveFile = wave.open(self.wf, 'rb') #initialize stream self.p = pyaudio.PyAudio() self.stream = self.p.open(format = self.p.get_format_from_width(self.waveFile.getsampwidth()), channels = self.waveFile.getnchannels(), rate = self.waveFile.getframerate(), output = True) self.data = self.waveFile.readframes(1024) isPaused = False isStopped = False #main play loop, with pause event checking while self.data != '': # while isPaused != True: # if isStopped == False: self.stream.write(self.data) self.data = self.waveFile.readframes(1024) # elif isStopped == True: # self.stream.close() # self.p.terminate() self.stream.close() self.p.terminate() class App(wx.App): def OnInit(self): self.frame = Frame() self.frame.Show() self.SetTopWindow(self.frame) return True def main(): app = App() app.MainLoop() if __name__=='__main__': main()

    Read the article

  • win7: app crashing/hanging on "save as"-dialog

    - by Fuxi
    hi all, now this is really annoying - i'm having a global problem in win7: when using the system's "save as"-filedialog, the main app will just hang. the mouse-cursor is showing progress, the whole app is hanging and i need to terminate it manually. it's happening with every app! (notepad, word, graphics app). i'm assuming it's something with the system enumerating the harddisk-drivenames or something. any idea how to fix this? btw - when viewing the problem details - it's telling the module - it's msonsext.dll looks like some office thing to me. thanks

    Read the article

  • swf file upload control not filtering the files for the second time

    - by subash
    iam using swf file upload control in my application developed in asp.net & c#.net. i am having a dropdown box with file types like jpeg,.xls ,.txt etc. so when i select particular file type in the dropdown and clicking on the button would open a filedialog showing only the files of the type selected in the dropdown. The problem is that when i select "jpeg" for the first time file dialog shows only jpeg files. when i select ".xls" next time it shows again the prevoiusly selected jpeg files and not currently selected ".xls". but while debugging it was found the file type definition in the swf code has been changed to .xls . can any one guide why the file upload control not mapping the selected file for the second time

    Read the article

  • Python Threading, loading one thread after another

    - by Michael
    Hi, I'm working on a media player and am able to load in a single .wav and play it. As seen in the code below. foo = wx.FileDialog(self, message="Open a .wav file...", defaultDir=os.getcwd(), defaultFile="", style=wx.FD_MULTIPLE) foo.ShowModal() queue = foo.GetPaths() self.playing_thread = threading.Thread(target=self.playFile, args=(queue[0], 'msg')) self.playing_thread.start() But the problem is, when I try to make the above code into a loop for multiple .wav files. Such that while playing_thread.isActive == True, create and .start() the thread. Then if .isActive == False, pop queue[0] and load the next .wav file. Problem is, my UI will lock up and I'll have to terminate the program. Any ideas would be appreciated.

    Read the article

  • Is it possible to have file filters for multiple extension types?

    - by Jon Cage
    I'm using a standard Windows FileDialog to allow the user to select some files. I'd like to filter out only the file types I'm interested in though (lets call them *.a and *.b). Is there any way to do this without using *.*? I've tried the following but it fails to match any files at all: this->openFileDialog1->DefaultExt = L"*.a,*.b"; this->openFileDialog1->FileName = L"openFileDialog1"; this->openFileDialog1->Filter = L"My Data Files (*.a,*.b)|*.a,*.b";

    Read the article

  • Save Bitmap image in a location in C#

    - by acadia
    Hello, I have this function to store the bmp image in a desired location as shown below My question is, how do I save the image in C:\temp folder by default, instead of opening the filedialog box? I want to specify sd.fileName=picname+".bmp" and store it in c:\temp by default. I tried to specify Thanks for your help in advance. I tried to public static bool SaveDIBAs( string picname, IntPtr bminfo, IntPtr pixdat ) { SaveFileDialog sd = new SaveFileDialog(); sd.FileName = picname; sd.Title = "Save bitmap as..."; sd.Filter = "Bitmap file (*.bmp)|*.bmp|TIFF file (*.tif)|*.tif|JPEG file (*.jpg)|*.jpg|PNG file (*.png)|*.png|GIF file (*.gif)|*.gif|All files (*.*)|*.*"; sd.FilterIndex = 1; if( sd.ShowDialog() != DialogResult.OK ) return false; Guid clsid; if( ! GetCodecClsid( sd.FileName, out clsid ) ) { MessageBox.Show( "Unknown picture format for extension " + Path.GetExtension( sd.FileName ), "Image Codec", MessageBoxButtons.OK, MessageBoxIcon.Information ); return false; } IntPtr img = IntPtr.Zero; int st = GdipCreateBitmapFromGdiDib( bminfo, pixdat, ref img ); if( (st != 0) || (img == IntPtr.Zero) ) return false; st = GdipSaveImageToFile( img, sd.FileName, ref clsid, IntPtr.Zero ); GdipDisposeImage( img ); return st == 0; }

    Read the article

  • PGU HTML Renderer can't render most sites

    - by None
    I am trying to make a web browser using pygame. I am using PGU for html rendering. It works fine when I visit simple sites, like example.com, but when I try and load anything more complex that uses an html form, like google, I get this error: UnboundLocalError: local variable 'e' referenced before assignment I looked in the PGU html rendering file and found this code segment: def start_input(self,attrs): r = self.attrs_to_map(attrs) params = self.map_to_params(r) #why bother #params = {} type_,name,value = r.get('type','text'),r.get('name',None),r.get('value',None) f = self.form if type_ == 'text': e = gui.Input(**params) self.map_to_connects(e,r) self.item.add(e) elif type_ == 'radio': if name not in f.groups: f.groups[name] = gui.Group(name=name) g = f.groups[name] del params['name'] e = gui.Radio(group=g,**params) self.map_to_connects(e,r) self.item.add(e) if 'checked' in r: g.value = value elif type_ == 'checkbox': if name not in f.groups: f.groups[name] = gui.Group(name=name) g = f.groups[name] del params['name'] e = gui.Checkbox(group=g,**params) self.map_to_connects(e,r) self.item.add(e) if 'checked' in r: g.value = value elif type_ == 'button': e = gui.Button(**params) self.map_to_connects(e,r) self.item.add(e) elif type_ == 'submit': e = gui.Button(**params) self.map_to_connects(e,r) self.item.add(e) elif type_ == 'file': e = gui.Input(**params) self.map_to_connects(e,r) self.item.add(e) b = gui.Button(value='Browse...') self.item.add(b) def _browse(value): d = gui.FileDialog(); d.connect(gui.CHANGE,gui.action_setvalue,(d,e)) d.open(); b.connect(gui.CLICK,_browse,None) self._locals[r.get('id',None)] = e I got the error in the last line, because e wasn't defined. I am guessing the reason for this is that the if statement that checks the type of the input and creates the e variable didn't match anything. I added a line to print the _type variable and I got 'hidden' when i tried google and apple. Is there any way to render form items that have the type 'hidden' with PGU?

    Read the article

  • How to edit item in a listbox shown from reading a .csv file?

    - by Shuvo
    I am working in a project where my application can open a .csv file and read data from it. The .csv file contains the latitude, longitude of places. The application reads data from the file shows it in a static map and display icon on the right places. The application can open multiple file at a time and it opens with a new tab every time. But I am having trouble in couple of cases When I am trying to add a new point to the .csv file opened. I am able to write new point on the same file instead adding a new point data to the existing its replacing others and writing the new point only. I cannot use selectedIndexChange event to perform edit option on the listbox and then save the file. Any direction would be great. using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.IO; namespace CourseworkExample { public partial class Form1 : Form { public GPSDataPoint gpsdp; List<GPSDataPoint> data; List<PictureBox> pictures; List<TabPage> tabs; public static int pn = 0; private TabPage currentComponent; private Bitmap bmp1; string[] symbols = { "hospital", "university" }; Image[] symbolImages; ListBox lb = new ListBox(); string name = ""; string path = ""; public Form1() { InitializeComponent(); data = new List<GPSDataPoint>(); pictures = new List<PictureBox>(); tabs = new List<TabPage>(); symbolImages = new Image[symbols.Length]; for (int i = 0; i < 2; i++) { string location = "data/" + symbols[i] + ".png"; symbolImages[i] = Image.FromFile(location); } } private void openToolStripMenuItem_Click(object sender, EventArgs e) { FileDialog ofd = new OpenFileDialog(); string filter = "CSV File (*.csv)|*.csv"; ofd.Filter = filter; DialogResult dr = ofd.ShowDialog(); if (dr.Equals(DialogResult.OK)) { int i = ofd.FileName.LastIndexOf("\\"); name = ofd.FileName; path = ofd.FileName; if (i > 0) { name = ofd.FileName.Substring(i + 1); path = ofd.FileName.Substring(0, i + 1); } TextReader input = new StreamReader(ofd.FileName); string mapName = input.ReadLine(); GPSDataPoint gpsD = new GPSDataPoint(); gpsD.setBounds(input.ReadLine()); string s; while ((s = input.ReadLine()) != null) { gpsD.addWaypoint(s); } input.Close(); TabPage tabPage = new TabPage(); tabPage.Location = new System.Drawing.Point(4, 22); tabPage.Name = "tabPage" + pn; lb.Width = 300; int selectedindex = lb.SelectedIndex; lb.Items.Add(mapName); lb.Items.Add("Bounds"); lb.Items.Add(gpsD.Bounds[0] + " " + gpsD.Bounds[1] + " " + gpsD.Bounds[2] + " " + gpsD.Bounds[3]); lb.Items.Add("Waypoint"); foreach (WayPoint wp in gpsD.DataList) { lb.Items.Add(wp.Name + " " + wp.Latitude + " " + wp.Longitude + " " + wp.Ele + " " + wp.Sym); } tabPage.Controls.Add(lb); pn++; tabPage.Padding = new System.Windows.Forms.Padding(3); tabPage.Size = new System.Drawing.Size(192, 74); tabPage.TabIndex = 0; tabPage.Text = name; tabPage.UseVisualStyleBackColor = true; tabs.Add(tabPage); tabControl1.Controls.Add(tabPage); tabPage = new TabPage(); tabPage.Location = new System.Drawing.Point(4, 22); tabPage.Name = "tabPage" + pn; pn++; tabPage.Padding = new System.Windows.Forms.Padding(3); tabPage.Size = new System.Drawing.Size(192, 74); tabPage.TabIndex = 0; tabPage.Text = mapName; string location = path + mapName; tabPage.UseVisualStyleBackColor = true; tabs.Add(tabPage); PictureBox pb = new PictureBox(); pb.Name = "pictureBox" + pn; pb.Image = Image.FromFile(location); tabControl2.Controls.Add(tabPage); pb.Width = pb.Image.Width; pb.Height = pb.Image.Height; tabPage.Controls.Add(pb); currentComponent = tabPage; tabPage.Width = pb.Width; tabPage.Height = pb.Height; pn++; tabControl2.Width = pb.Width; tabControl2.Height = pb.Height; bmp1 = (Bitmap)pb.Image; int lx, ly; float realWidth = gpsD.Bounds[1] - gpsD.Bounds[3]; float imageW = pb.Image.Width; float dx = imageW * (gpsD.Bounds[1] - gpsD.getWayPoint(0).Longitude) / realWidth; float realHeight = gpsD.Bounds[0] - gpsD.Bounds[2]; float imageH = pb.Image.Height; float dy = imageH * (gpsD.Bounds[0] - gpsD.getWayPoint(0).Latitude) / realHeight; lx = (int)dx; ly = (int)dy; using (Graphics g = Graphics.FromImage(bmp1)) { Rectangle rect = new Rectangle(lx, ly, 20, 20); if (gpsD.getWayPoint(0).Sym.Equals("")) { g.DrawRectangle(new Pen(Color.Red), rect); } else { if (gpsD.getWayPoint(0).Sym.Equals("hospital")) { g.DrawImage(symbolImages[0], rect); } else { if (gpsD.getWayPoint(0).Sym.Equals("university")) { g.DrawImage(symbolImages[1], rect); } } } } pb.Image = bmp1; pb.Invalidate(); } } private void openToolStripMenuItem_Click_1(object sender, EventArgs e) { FileDialog ofd = new OpenFileDialog(); string filter = "CSV File (*.csv)|*.csv"; ofd.Filter = filter; DialogResult dr = ofd.ShowDialog(); if (dr.Equals(DialogResult.OK)) { int i = ofd.FileName.LastIndexOf("\\"); name = ofd.FileName; path = ofd.FileName; if (i > 0) { name = ofd.FileName.Substring(i + 1); path = ofd.FileName.Substring(0, i + 1); } TextReader input = new StreamReader(ofd.FileName); string mapName = input.ReadLine(); GPSDataPoint gpsD = new GPSDataPoint(); gpsD.setBounds(input.ReadLine()); string s; while ((s = input.ReadLine()) != null) { gpsD.addWaypoint(s); } input.Close(); TabPage tabPage = new TabPage(); tabPage.Location = new System.Drawing.Point(4, 22); tabPage.Name = "tabPage" + pn; ListBox lb = new ListBox(); lb.Width = 300; lb.Items.Add(mapName); lb.Items.Add("Bounds"); lb.Items.Add(gpsD.Bounds[0] + " " + gpsD.Bounds[1] + " " + gpsD.Bounds[2] + " " + gpsD.Bounds[3]); lb.Items.Add("Waypoint"); foreach (WayPoint wp in gpsD.DataList) { lb.Items.Add(wp.Name + " " + wp.Latitude + " " + wp.Longitude + " " + wp.Ele + " " + wp.Sym); } tabPage.Controls.Add(lb); pn++; tabPage.Padding = new System.Windows.Forms.Padding(3); tabPage.Size = new System.Drawing.Size(192, 74); tabPage.TabIndex = 0; tabPage.Text = name; tabPage.UseVisualStyleBackColor = true; tabs.Add(tabPage); tabControl1.Controls.Add(tabPage); tabPage = new TabPage(); tabPage.Location = new System.Drawing.Point(4, 22); tabPage.Name = "tabPage" + pn; pn++; tabPage.Padding = new System.Windows.Forms.Padding(3); tabPage.Size = new System.Drawing.Size(192, 74); tabPage.TabIndex = 0; tabPage.Text = mapName; string location = path + mapName; tabPage.UseVisualStyleBackColor = true; tabs.Add(tabPage); PictureBox pb = new PictureBox(); pb.Name = "pictureBox" + pn; pb.Image = Image.FromFile(location); tabControl2.Controls.Add(tabPage); pb.Width = pb.Image.Width; pb.Height = pb.Image.Height; tabPage.Controls.Add(pb); currentComponent = tabPage; tabPage.Width = pb.Width; tabPage.Height = pb.Height; pn++; tabControl2.Width = pb.Width; tabControl2.Height = pb.Height; bmp1 = (Bitmap)pb.Image; int lx, ly; float realWidth = gpsD.Bounds[1] - gpsD.Bounds[3]; float imageW = pb.Image.Width; float dx = imageW * (gpsD.Bounds[1] - gpsD.getWayPoint(0).Longitude) / realWidth; float realHeight = gpsD.Bounds[0] - gpsD.Bounds[2]; float imageH = pb.Image.Height; float dy = imageH * (gpsD.Bounds[0] - gpsD.getWayPoint(0).Latitude) / realHeight; lx = (int)dx; ly = (int)dy; using (Graphics g = Graphics.FromImage(bmp1)) { Rectangle rect = new Rectangle(lx, ly, 20, 20); if (gpsD.getWayPoint(0).Sym.Equals("")) { g.DrawRectangle(new Pen(Color.Red), rect); } else { if (gpsD.getWayPoint(0).Sym.Equals("hospital")) { g.DrawImage(symbolImages[0], rect); } else { if (gpsD.getWayPoint(0).Sym.Equals("university")) { g.DrawImage(symbolImages[1], rect); } } } } pb.Image = bmp1; pb.Invalidate(); MessageBox.Show(data.ToString()); } } private void exitToolStripMenuItem_Click(object sender, EventArgs e) { this.Close(); } private void addBtn_Click(object sender, EventArgs e) { string wayName = nameTxtBox.Text; float wayLat = Convert.ToSingle(latTxtBox.Text); float wayLong = Convert.ToSingle(longTxtBox.Text); float wayEle = Convert.ToSingle(elevTxtBox.Text); WayPoint wp = new WayPoint(wayName, wayLat, wayLong, wayEle); GPSDataPoint gdp = new GPSDataPoint(); data = new List<GPSDataPoint>(); gdp.Add(wp); lb.Items.Add(wp.Name + " " + wp.Latitude + " " + wp.Longitude + " " + wp.Ele + " " + wp.Sym); lb.Refresh(); StreamWriter sr = new StreamWriter(name); sr.Write(lb); sr.Close(); DialogResult result = MessageBox.Show("Save in New File?","Save", MessageBoxButtons.YesNo); if (result == DialogResult.Yes) { SaveFileDialog saveDialog = new SaveFileDialog(); saveDialog.FileName = "default.csv"; DialogResult saveResult = saveDialog.ShowDialog(); if (saveResult == DialogResult.OK) { sr = new StreamWriter(saveDialog.FileName, true); sr.WriteLine(wayName + "," + wayLat + "," + wayLong + "," + wayEle); sr.Close(); } } else { // sr = new StreamWriter(name, true); // sr.WriteLine(wayName + "," + wayLat + "," + wayLong + "," + wayEle); sr.Close(); } MessageBox.Show(name + path); } } } GPSDataPoint.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace CourseworkExample { public class GPSDataPoint { private float[] bounds; private List<WayPoint> dataList; public GPSDataPoint() { dataList = new List<WayPoint>(); } internal void setBounds(string p) { string[] b = p.Split(','); bounds = new float[b.Length]; for (int i = 0; i < b.Length; i++) { bounds[i] = Convert.ToSingle(b[i]); } } public float[] Bounds { get { return bounds; } } internal void addWaypoint(string s) { WayPoint wp = new WayPoint(s); dataList.Add(wp); } public WayPoint getWayPoint(int i) { if (i < dataList.Count) { return dataList[i]; } else return null; } public List<WayPoint> DataList { get { return dataList; } } internal void Add(WayPoint wp) { dataList.Add(wp); } } } WayPoint.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CourseworkExample { public class WayPoint { private string name; private float ele; private float latitude; private float longitude; private string sym; public WayPoint(string name, float latitude, float longitude, float elevation) { this.name = name; this.latitude = latitude; this.longitude = longitude; this.ele = elevation; } public WayPoint() { name = "no name"; ele = 3.5F; latitude = 3.5F; longitude = 0.0F; sym = "no symbol"; } public WayPoint(string s) { string[] bits = s.Split(','); name = bits[0]; longitude = Convert.ToSingle(bits[2]); latitude = Convert.ToSingle(bits[1]); if (bits.Length > 4) sym = bits[4]; else sym = ""; try { ele = Convert.ToSingle(bits[3]); } catch (Exception e) { ele = 0.0f; } } public float Longitude { get { return longitude; } set { longitude = value; } } public float Latitude { get { return latitude; } set { latitude = value; } } public float Ele { get { return ele; } set { ele = value; } } public string Name { get { return name; } set { name = value; } } public string Sym { get { return sym; } set { sym = value; } } } } .csv file data birthplace.png 51.483788,-0.351906,51.460745,-0.302982 Born Here,51.473805,-0.32532,-,hospital Danced here,51,483805,-0.32532,-,hospital

    Read the article

  • Multiple data series in real time plot

    - by Gr3n
    Hi, I'm kind of new to Python and trying to create a plotting app for values read via RS232 from a sensor. I've managed (after some reading and copying examples online) to get a plot working that updates on a timer which is great. My only trouble is that I can't manage to get multiple data series into the same plot. Does anyone have a solution to this? This is the code that I've worked out this far: import os import pprint import random import sys import wx # The recommended way to use wx with mpl is with the WXAgg backend import matplotlib matplotlib.use('WXAgg') from matplotlib.figure import Figure from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigCanvas, NavigationToolbar2WxAgg as NavigationToolbar import numpy as np import pylab DATA_LENGTH = 100 REDRAW_TIMER_MS = 20 def getData(): return int(random.uniform(1000, 1020)) class GraphFrame(wx.Frame): # the main frame of the application def __init__(self): wx.Frame.__init__(self, None, -1, "Usart plotter", size=(800,600)) self.Centre() self.data = [] self.paused = False self.create_menu() self.create_status_bar() self.create_main_panel() self.redraw_timer = wx.Timer(self) self.Bind(wx.EVT_TIMER, self.on_redraw_timer, self.redraw_timer) self.redraw_timer.Start(REDRAW_TIMER_MS) def create_menu(self): self.menubar = wx.MenuBar() menu_file = wx.Menu() m_expt = menu_file.Append(-1, "&Save plot\tCtrl-S", "Save plot to file") self.Bind(wx.EVT_MENU, self.on_save_plot, m_expt) menu_file.AppendSeparator() m_exit = menu_file.Append(-1, "E&xit\tCtrl-X", "Exit") self.Bind(wx.EVT_MENU, self.on_exit, m_exit) self.menubar.Append(menu_file, "&File") self.SetMenuBar(self.menubar) def create_main_panel(self): self.panel = wx.Panel(self) self.init_plot() self.canvas = FigCanvas(self.panel, -1, self.fig) # pause button self.pause_button = wx.Button(self.panel, -1, "Pause") self.Bind(wx.EVT_BUTTON, self.on_pause_button, self.pause_button) self.Bind(wx.EVT_UPDATE_UI, self.on_update_pause_button, self.pause_button) self.hbox1 = wx.BoxSizer(wx.HORIZONTAL) self.hbox1.Add(self.pause_button, border=5, flag=wx.ALL | wx.ALIGN_CENTER_VERTICAL) self.vbox = wx.BoxSizer(wx.VERTICAL) self.vbox.Add(self.canvas, 1, flag=wx.LEFT | wx.TOP | wx.GROW) self.vbox.Add(self.hbox1, 0, flag=wx.ALIGN_LEFT | wx.TOP) self.panel.SetSizer(self.vbox) #self.vbox.Fit(self) def create_status_bar(self): self.statusbar = self.CreateStatusBar() def init_plot(self): self.dpi = 100 self.fig = Figure((3.0, 3.0), dpi=self.dpi) self.axes = self.fig.add_subplot(111) self.axes.set_axis_bgcolor('white') self.axes.set_title('Usart data', size=12) pylab.setp(self.axes.get_xticklabels(), fontsize=8) pylab.setp(self.axes.get_yticklabels(), fontsize=8) # plot the data as a line series, and save the reference # to the plotted line series # self.plot_data = self.axes.plot( self.data, linewidth=1, color="blue", )[0] def draw_plot(self): # redraws the plot xmax = len(self.data) if len(self.data) > DATA_LENGTH else DATA_LENGTH xmin = xmax - DATA_LENGTH ymin = 0 ymax = 4096 self.axes.set_xbound(lower=xmin, upper=xmax) self.axes.set_ybound(lower=ymin, upper=ymax) # enable grid #self.axes.grid(True, color='gray') # Using setp here is convenient, because get_xticklabels # returns a list over which one needs to explicitly # iterate, and setp already handles this. # pylab.setp(self.axes.get_xticklabels(), visible=True) self.plot_data.set_xdata(np.arange(len(self.data))) self.plot_data.set_ydata(np.array(self.data)) self.canvas.draw() def on_pause_button(self, event): self.paused = not self.paused def on_update_pause_button(self, event): label = "Resume" if self.paused else "Pause" self.pause_button.SetLabel(label) def on_save_plot(self, event): file_choices = "PNG (*.png)|*.png" dlg = wx.FileDialog( self, message="Save plot as...", defaultDir=os.getcwd(), defaultFile="plot.png", wildcard=file_choices, style=wx.SAVE) if dlg.ShowModal() == wx.ID_OK: path = dlg.GetPath() self.canvas.print_figure(path, dpi=self.dpi) self.flash_status_message("Saved to %s" % path) def on_redraw_timer(self, event): if not self.paused: newData = getData() self.data.append(newData) self.draw_plot() def on_exit(self, event): self.Destroy() def flash_status_message(self, msg, flash_len_ms=1500): self.statusbar.SetStatusText(msg) self.timeroff = wx.Timer(self) self.Bind( wx.EVT_TIMER, self.on_flash_status_off, self.timeroff) self.timeroff.Start(flash_len_ms, oneShot=True) def on_flash_status_off(self, event): self.statusbar.SetStatusText('') if __name__ == '__main__': app = wx.PySimpleApp() app.frame = GraphFrame() app.frame.Show() app.MainLoop()

    Read the article

1