SoulMazer 26 Posting Whiz in Training

It just so happens I used this exact library to store information for my media player! I cleaned up the code a bit and just included some basic operations. (songDict is a dictionary which contains the name, artist, album, etc. of various songs -- I find it easiest to put information already in a dictionary into a database)

#!/usr/bin/python
# sqlite3 example

import sqlite3

"""
songDict:
the key is the song
songDict[0] = path
songDict[1] = artist
songDict[2] = album
"""

class Database:
    def __init__(self):
        try:
            self.conn = sqlite3.connect('songs.db')
        except sqlite3.OperationalError: # Can't locate database file
            exit(1)
        self.cursor = self.conn.cursor()
        
    def createDatabase(self):
        cmd = "CREATE TABLE allsongs(path VARCHAR(100), name VARCHAR(50), artist VARCHAR(50), album VARCHAR(50))"
        self.cursor.execute(cmd)
        self.conn.commit()
        
    def insertSongs(self, songDict):
        for song in songDict:
            cmd = """INSERT INTO allsongs(path, name, artist, album) VALUES("%s", "%s", "%s", "%s")""" % (song, songDict[song][0], songDict[song][1], songDict[song][2])
            print "Inserting", song+"..."
            self.cursor.execute(cmd)
        
        self.conn.commit()
        
    def getSongs(self):
        songDict = {}
        cmd = "SELECT * FROM allsongs"
        self.cursor.execute(cmd)
        results = self.cursor.fetchall()
        for song in results:
            songDict[song[0]] = (song[1], song[2], song[3])

        return songDict
        
    def closeHandle(self):
        'Closes the connection to the database'
        self.conn.commit() # Make sure all changes are saved
        self.conn.close()

If you want me to explain any of it, feel free to ask.

SoulMazer 26 Posting Whiz in Training

Okay, I'm not sure what's going on, but tkSnack (link) is deciding to not work for me all of a sudden. I have written a full-blown freaking media player with it, and I am now failing to simply play a song from the command line. I can get it to work in an interactive Python shell, but nothing more. Here is the code I am using:

from Tkinter import *
import tkSnack

root = Tk()
root.withdraw()
tkSnack.initializeSnack(root)
sound = tkSnack.Sound(load="/home/foo/song.mp3")
sound.play()

I just...have no idea why something this simple is not working. Could somebody help me out? Am I just tired or should this not be happening?

Thanks in advance.

SoulMazer 26 Posting Whiz in Training

Yes, you should probably just copy that code into a separate file and then import it into your program. From there, you can create the widget in your main script similarly to a normal widget. This example would be some sort of a music player:

import MultiListbox

frame = Frame(root, relief=SUNKEN)
mlb = MultiListbox.MultiListbox(frame, (('Title', 15), ('Artist', 15), ('Length', 12)))
for i in range(1000):
    mlb.insert(END, ('Test Song %d' % i, 'Test Artist %d' % i, 'Length %d' % i))
mlb.pack(expand=YES,fill=BOTH)

Post back if you have any other questions.

SoulMazer 26 Posting Whiz in Training

Well, I had the same exact problem a few months ago. I used the code found here (link), and found it is pretty good, but not perfect. For example, if you click within one of the listboxes and scroll with the mouse wheel, they do not scroll synchronously. But that's the best I could find. Good luck.

SoulMazer 26 Posting Whiz in Training

Sorry for resurrecting the old thread, but I thought I would post the solution to my problem. On line 8 of my code, I create a multiline TextCtrl widget to put my text in. On Linux, this is all that is needed in order to style text. However, in Windows, you must add the wx.TE_RICH2 attribute to a TextCtrl widget in order to do this.

SoulMazer 26 Posting Whiz in Training

Wow, dumb mistake on my part. I actually posted this exact same problem a few months ago. As I can see many people do not want to download my attached files, I provided a code example in my other thread.

Link:
http://www.daniweb.com/forums/thread275016.html

EDIT: Haha! I solved my own problem after some more research. So, I guess Windows and Linux differ in the fact that in order to change the style of text, Windows wants TextCtrl widgets to have the wx.TE_RICH2 attribute, while Linux does not need it. Quite strange.

SoulMazer 26 Posting Whiz in Training

Hi, I'm trying to color some text with wxPython but I am having some trouble. I am using the SetStyle method of the TextCtrl widget. My problem is that the coloring works perfectly on Linux but does not under Windows.

My script basically gives a vocabulary test, and if you get a word correct, it should color the phrase "Correct!" green. Likewise, if you get it incorrect, "That is incorrect. Try again" should be colored red.

Rather than create a whole new example, I just attached my code in a .zip file. Just run wxVocabTest.py (only dependency is wxPython) and you will be able to see the problem.

So, why does it color fine in Linux but not Windows?

Thanks in advance.

SoulMazer 26 Posting Whiz in Training

Well, I know of a project that would definitely prove beneficial to the community if it was wrapped in python. Xfire. If you haven't heard of it, its an instant messaging program for Windows only. Somebody created a library for it in C, but that's it. There is only one client based of this library for Linux, which doesnt always work. If you could write a wrapper for python, I would definitely write a cross platform client so that Xfire could be accessed from any OS. Here's the link to the c library: http://code.google.com/p/openfire-c/

I think that would be a good place to start.

SoulMazer 26 Posting Whiz in Training

As for your mouse problem, I think I may have a solution. Right now, I assume you are binding the Enter and Space keys to your txt1_onText method. If you're just having trouble setting your EndP variable when the user clicks away, why not just bind the mouse to a transition method before the program has a chance to change the insertion point? You can do this by binding a mouse click to a method that calls your txt1_onText method before the cursor is moved by the program:

# Wherever you do your bindings
self.txt1.Bind(wx.EVT_LEFT_DOWN, self.txt1_onText)


def mouseClick(self, event):
    self.txt1_onText(event=None) # Wait until you get your EndP data before continuing with the event (next line)
    event.Skip()

Does this solve the mouse problem?

SoulMazer 26 Posting Whiz in Training

That's exactly what I needed. Perfect. Thanks woooee, you're a great help.

SoulMazer 26 Posting Whiz in Training

When you say you are currently sending code between client and server on the same machine, how are you doing this? Via a local socket or what?

If so, you just need to give the client the IP address/port of the server and connect via the "connect" method of your socket object and you will be good to go.

If not, just post back and I'll try to help you out.

SoulMazer 26 Posting Whiz in Training

Like I said, it works, but only up to a point.

What do you mean by this? So can you correctly highlight words? If so, what is your problem?

Also, could you post your code? I'd love to dive into this and come up with a solution, as it would prove to be helpful to one of the scripts I'm writing.

EDIT: Okay, I think after some re-reading I understand your problem a little better. So your problem is when the user strays away from the current word by using the arrow keys/mouse/etc? Post your code and I could help you.

SoulMazer 26 Posting Whiz in Training

Okay, I am writing a script that might be impossible to fully explain in words. Therefore, I am going to come up with an example that shows the same problem, so please do not tell me to simply combine the scripts or anything, as I am unable to.

Anyways, I have "MyScript.py" and "MyScriptGUI.py". MyScriptGUI is supposed to be like a library, so let's pretend I am not able to edit its code. MyScriptGUI's code looks like this:

#!/usr/bin/python
# MyScriptGUI.py

class GUIClass:
    
    def __init__(self):
        # create a text area named "textArea"
        # bind the function "OnEnterDown" to the Enter key
        
    def OnEnterDown(self):
        # Call the function 'combine' in MyScript.py

Here is the code for MyScript:

#!/usr/bin/python
# MyScript.py

import random

class MyClass:
    
    def __init__(self):
        self.myNumber = random.randint(1, 10)
        self.myWord = "Hello"
        
    def combine(self): # I want this function to be called when the Enter key is pressed
        phrase = self.myWord+str(self.myNumber)
        print phrase

So, how would I go about calling the 'combine' method in MyScript.py? I cannot create a new instance from within MyScriptGUI.py, since I obviously need to preserve the values of "self.myNumber" and "self.myWord" in order to run the 'combine' method. If I create a new instance, these will be lost.

Any ideas?

EDIT: I figured out that I can do this crudely by passing the 'self' argument to the GUI script, but I would rather not do that unless it is the only way.

SoulMazer 26 Posting Whiz in Training

The code looks a lot better now. It's very smart to only handle text writing via one function/thread, this will hopefully prevent any further errors. Clever use of CallAfter too.

SoulMazer 26 Posting Whiz in Training

I'm not exactly sure what you're trying to say but I'll try to help you. From what I understand, you want to search through a text file for a certain word denoted by the variable 'text1' and print the line number in which it is found?

If so, try this:

#!/usr/bin/python

text1 = "the" # Change to whatever you would like
lineNumber = 0

f = open("words.txt", "r")
for line in f.readlines():
    lineNumber += 1
    if text1 in line:
        print "Word found at line", lineNumber
SoulMazer 26 Posting Whiz in Training

Rather than having to wait for a socket to time out to allow the rest of your program to execute, you could always use threading. Then you wouldn't have to worry about a timeout or anything, you could just have one thread receive packets while the other one does whatever other action you want to do. Post back if you have any questions about how to do that.

However, if you do not want to use threading, the reason you are having that error is because there is no data waiting to be read from the socket. A much easier way to check if there is data on a socket is using the select module. That way, rather than using a socket timeout, you could do something like this:

### THIS IS PSEUDOCODE
if socket has data:
    receivePacket()
else:
    doSomethingElse()
SoulMazer 26 Posting Whiz in Training

Try this:

#!/usr/bin/python

import threading

class Client1Thread(threading.Thread):
    
    def __init__(self, param1, param2):
	threading.Thread.__init__(self)
	self.param1 = param1
	self.param2 = param2
	
    def run(self):
	print "[Client1 Thread] The value of param1 is", self.param1
	print "[Client1 Thread] The value of param2 is", self.param2
	# Enter code here for client 1
	

class Client2Thread(threading.Thread):
    
    def __init__(self, param1, param2):
	threading.Thread.__init__(self)
	self.param1 = param1
	self.param2 = param2
	
    def run(self):
	print "[Client2 Thread] The value of param1 is", self.param1
	print "[Client2 Thread] The value of param2 is", self.param2
	# Enter code here for client 2
	
threadOne = Client1Thread("hello", "world")
threadTwo = Client2Thread(12, 15)

threadOne.start()
threadTwo.start()
SoulMazer 26 Posting Whiz in Training

Hi, I'm writing a media player with wxPython and I seem to be having a bit of trouble. In my script, I create a wx.media.MediaCtrl widget; this line of code causes the trouble. On my Linux machine (running wxPython 2.8), this line of code causes no trouble at all. However, on my Windows Vista machine (also running wxPython 2.8), it causes all sorts of problems. Once the interpreter reaches this line in my code, it just quits. No error in the terminal. Nothing. I just get a little Vista box saying "python.exe has stopped working."

Even if I put a "try/except" statement around it, nothing changes. No error is raised at all.

What is causing this to occur on solely Windows? Both machines run the same versions of Python and wxPython...what is the problem here?

Thanks in advance.

EDIT: I can reproduce this error by running the following code:

import wx
import wx.media

myApp = wx.App()
mc = wx.media.MediaCtrl(None)

EDIT 2: Well, I think I've just about sorted it all out. On Windows Vista, if you create a wx.media.MediaCtrl widget, you MUST supply a parent, or you face the consequences. However, you are allowed to create it without a parent on Linux. Why is this?

SoulMazer 26 Posting Whiz in Training

When I started threading in Python, I had the exact same problem. It's quite difficult to find a very basic example of it. Let me try to give you one using the scenario you described.

I'm not quite sure how you are going to connect to the two client machines, so I'll leave that up to you. This is probably the most simple threading example you can have:

#!/usr/bin/python

import threading

class Client1Thread(threading.Thread):
    
    def __init__(self):
	threading.Thread.__init__(self)
	
    def run(self):
	print "Running the Client1 Thread"
	# Enter code here for client 1
	

class Client2Thread(threading.Thread):
    
    def __init__(self):
	threading.Thread.__init__(self)
	
    def run(self):
	print "Running the Client2 Thread"
	# Enter code here for client 2
	
threadOne = Client1Thread()
threadTwo = Client2Thread()

threadOne.start()
threadTwo.start()

If you need help with any of it, feel free to post back.

EDIT: There's a code snippet by a1eio that also shows a basic example of threading quite well. Link.

SoulMazer 26 Posting Whiz in Training

The reason it is not working is because you are splitting it up into two different sections. You need to move your if statement inside the while loop. It should be like this:

def used():
    used = 0
    while (used < 0):
        used = input("how many minutes were used")
        if (used < 0):
            print "enter minutes used of at least 0"
    return used
SoulMazer 26 Posting Whiz in Training

First of all, please wrap your code in code tags. It will save everybody on the forum a great deal of pain.

Anyways, back to your problem. Try replacing your "mins" function with this one:

def mins():
    mins = 0 # Initialize the variable
    while (mins > 800) or (mins < 200):
        mins = input("how many minutes are allowed")
        if mins <200:
            print "Please enter minutes between 200 and 800"
        if mins >800:
            print "Please enter minutes between 200 and 800"
    return mins

EDIT: Admins/moderators, how do you put a code tag in a reply without creating a code box?

SoulMazer 26 Posting Whiz in Training

Ugg. Double post. Sorry.

SoulMazer 26 Posting Whiz in Training

The documentation is pretty much nonexistent, but you can find plenty of examples by searching the web for "python win32 simulate mouse click" or something similar.

Simulate a mouse click:

import win32api
import win32con

def click(x,y):
    win32api.SetCursorPos((x,y))
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, x, y, 0, 0)
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, x, y, 0, 0)

click(100, 100) # simulate mouse click at 100px, 100px

Simulate a key press:

Download SendKeys from here.
Then:

from SendKeys import SendKeys
SendKeys('Hello{SPACE}world{ENTER}')
SoulMazer 26 Posting Whiz in Training

So is there a possibility to get a macro, which presses keys and clicks when the user presses a key, written in python?

So, let me see if I have this right. You want a script to emulate mouse clicks/key presses when the user presses a certain key (ALT + F, for example)? If so, then it depends on what OS you're running. I'll assume you're running Windows for now.

This should get you started:

Download pyHook here.
Download win32 extensions (pythoncom) here.

#Detecting keystrokes as events
import pyHook
import pythoncom

def OnKeyboardEvent(event):
    print event.Ascii

hm = pyHook.HookManager()
hm.KeyDown = OnKeyboardEvent
hm.HookKeyboard()

while True:
    pythoncom.PumpMessages()

If you are by chance running Linux or another OS with X11 as its windowing system, I can give you one piece of advice: don't do it unless you have to. Just don't. If you're really determined, you can search for hours for some documentation for xbindkeys. If you need help with xbindkeys, post back. I have enough experience with it to help you get started.

Good luck with your scripting.

EDIT: If you want to do things the EASY way, check out AutoHotkey. You could probably write the entire script in about 5 minutes.

SoulMazer 26 Posting Whiz in Training

Hi, I've tried searching around for other problems similar to mine, and I was unable to find any. I seem to not be able to "color" text in a TextCtrl widget on Windows, but I can on Linux. I have a little screenshot and some code to show this:

Screenshot

Code:

#!/usr/bin/python

import wx

class MainWindow(wx.Frame):
    def __init__(self, parent, title, size_):
        wx.Frame.__init__(self, parent, title=title, size=size_)
        self.textArea = wx.TextCtrl(self, style=wx.TE_MULTILINE)
        self.textArea.AppendText("This text should be colored.")
        self.textArea.SetFocus()
        self.Show()
        self.colorText()
        
    def colorText(self):
        self.textArea.SetStyle(5, 9, wx.TextAttr("#ff9c00", "#000000"))

app = wx.PySimpleApp()
frame = MainWindow(None, "Example", (400,300))
app.MainLoop()

Is the SetStyle method not supported on Windows or what? Is there any way I could get around this problem? I think a while ago I read about being able to do this when you initiate the TextCtrl instance (line 8 of my code), by setting "style" equal to some special styling format, but I'm not positive about that.

Thanks in advance.

SoulMazer 26 Posting Whiz in Training

Hi, I'm writing a GUI app with wxPython and I am wondering how I would insert and read/parse accented letters (Spanish accents, for that matter) from a TextCtrl widget. Also, I would like this would be compatible with all platforms (Windows, Linux, etc.). How could I do this?

Thanks very much in advance.

SoulMazer 26 Posting Whiz in Training

Well, I think I may have found my solution. After running threads at different times or eliminating them altogether, I believe I may know what was causing the error. I believe two threads were occasionally trying to write to a text buffer simultaneously through the same instance and that just decimated everything. After making sure only one thread has access to the text buffer, the problem has ceased (for the last hour, at least).

So, I believe my problem has been solved; hopefully this can help somebody in the future.

SoulMazer 26 Posting Whiz in Training

I have a little bit of an update. I took my GUI "mainloop" out of a separate thread in hope I would get a more descriptive error message, which I did. Here are the two I get most frequently:

(python:2641): Gtk-WARNING **: Invalid text buffer iterator: either the iterator is uninitialized, or the characters/pixbufs/widgets in the buffer have been modified since the iterator was created.
You must use marks, character numbers, or line numbers to preserve a position across buffer modifications.
You can apply tags and insert marks without invalidating your iterators,
but any mutation that affects 'indexable' buffer contents (contents that can be referred to by character offset)
will invalidate all outstanding iterators

Segmentation fault

(python:2520): Gtk-CRITICAL **: gtk_text_layout_real_invalidate: assertion `layout->wrap_loop_count == 0' failed

Also, I frequently get a simple "Segmentation fault," with no other error message. What the heck is going on?

SoulMazer 26 Posting Whiz in Training

Sorry, I'm just having a little bit of trouble understanding what you are trying to say. Do you want me to have two threads running, and have one with a GUI and one without?

Let me try to explain my script a little further. The way I'm doing it right now, I only have two threads; thread one solely takes care of the "main loop" of the GUI, and the second thread wakes up every 100 milliseconds and checks the values of various variables in the script. If the values are as expected, it causes the GUI to change in some way.

Any other ideas on what could be causing this?

Thanks again.

SoulMazer 26 Posting Whiz in Training

Hi, I'm writing a multi-threaded script with wxPython as a GUI toolkit. About 50% of the time, I can run my script flawlessly. The other 50% of the time, I get huge errors regarding wxPython that I cannot seem to decipher; however, I think it could possibly be a problem with one of my lists? I'm not sure what information I post will be helpful, so just request whatever else you feel would be necessary in fixing this error. I will try to respond as promptly as I can.

OS: Ubuntu 9.10 64 bit
Python Version: 2.6

I guess I should probably start by simply posting the error. Here you go.

*** glibc detected *** python: corrupted double-linked list: 0x0000000001568f30 ***
======= Backtrace: =========
/lib/libc.so.6[0x7f16c76b2dd6]
/lib/libc.so.6[0x7f16c76b6452]
/lib/libc.so.6(__libc_malloc+0x6e)[0x7f16c76b782e]
/usr/lib/libfontconfig.so.1[0x7f16c3e12a4a]
/usr/lib/libfontconfig.so.1[0x7f16c3e12aeb]
/usr/lib/libfontconfig.so.1[0x7f16c3e12aeb]
/usr/lib/libfontconfig.so.1[0x7f16c3e12aeb]
/usr/lib/libfontconfig.so.1(FcConfigSubstituteWithPat+0x245)[0x7f16c3e12eb5]
/usr/lib/libpangocairo-1.0.so.0[0x7f16c2616400]
/usr/lib/libpangoft2-1.0.so.0[0x7f16c49dad7b]
/usr/lib/libpango-1.0.so.0[0x7f16c42d9113]
/usr/lib/libpango-1.0.so.0(pango_itemize_with_base_dir+0x70)[0x7f16c42d9790]
/usr/lib/libpango-1.0.so.0[0x7f16c42e1598]
/usr/lib/libpango-1.0.so.0[0x7f16c42e28fc]
/usr/lib/libgtk-x11-2.0.so.0(gtk_text_layout_get_line_display+0x616)[0x7f16c52a8b16]
/usr/lib/libgtk-x11-2.0.so.0(gtk_text_layout_get_iter_location+0xf8)[0x7f16c52aa948]
/usr/lib/libgtk-x11-2.0.so.0(gtk_text_view_scroll_to_iter+0x130)[0x7f16c52b79e0]
/usr/lib/libgtk-x11-2.0.so.0[0x7f16c52b7cb5]
/usr/lib/libgtk-x11-2.0.so.0[0x7f16c52b7d19]
/usr/lib/libgtk-x11-2.0.so.0[0x7f16c52b7d69]
/usr/lib/libgdk-x11-2.0.so.0[0x7f16c4e368c6]
/lib/libglib-2.0.so.0(g_main_context_dispatch+0x22e)[0x7f16c3325bce]
/lib/libglib-2.0.so.0[0x7f16c3329598]
/lib/libglib-2.0.so.0(g_main_loop_run+0x1a5)[0x7f16c33299f5]
/usr/lib/libgtk-x11-2.0.so.0(gtk_main+0xa7)[0x7f16c51ff177]
/usr/lib/libwx_gtk2u_core-2.6.so.0(_ZN11wxEventLoop3RunEv+0x53)[0x7f16c64dbc03]
/usr/lib/libwx_gtk2u_core-2.6.so.0(_ZN9wxAppBase8MainLoopEv+0x4b)[0x7f16c65581bb]
/usr/lib/python2.6/dist-packages/wx-2.6-gtk2-unicode/wx/_core_.so(_ZN7wxPyApp8MainLoopEv+0x37)[0x7f16c72d73d7]
/usr/lib/python2.6/dist-packages/wx-2.6-gtk2-unicode/wx/_core_.so[0x7f16c72f4d77]
python(PyEval_EvalFrameEx+0x4c89)[0x4a2299]
python(PyEval_EvalCodeEx+0x860)[0x4a40e0]
python[0x52be30]
python(PyObject_Call+0x47)[0x41d6e7]
python[0x4254ff]
python(PyObject_Call+0x47)[0x41d6e7]
python(PyEval_EvalFrameEx+0x438c)[0x4a199c]
python(PyEval_EvalFrameEx+0x5837)[0x4a2e47]
python(PyEval_EvalFrameEx+0x5837)[0x4a2e47]
python(PyEval_EvalFrameEx+0x5837)[0x4a2e47]
python(PyEval_EvalCodeEx+0x860)[0x4a40e0]
python[0x52be30]
python(PyObject_Call+0x47)[0x41d6e7]
python[0x4254ff]
python(PyObject_Call+0x47)[0x41d6e7]
python(PyEval_CallObjectWithKeywords+0x43)[0x49c623]
python[0x4d0bed]
/lib/libpthread.so.0[0x7f16c8254a04]
/lib/libc.so.6(clone+0x6d)[0x7f16c771c80d]
======= Memory map: ========
00400000-0060f000 r-xp 00000000 08:01 3875 /usr/bin/python2.6
0080e000-0080f000 r--p 0020e000 08:01 3875 /usr/bin/python2.6
0080f000-00870000 rw-p 0020f000 08:01 3875 /usr/bin/python2.6

SoulMazer 26 Posting Whiz in Training

Thanks for the feedback everybody, it was good advice. I think I will try it out and might even stay with it if I find to like the Tkinter improvements.

Thanks again everybody.

SoulMazer 26 Posting Whiz in Training

Hi, so I've been programming with Python (2.x) for a while now, and I was wondering about what people thought of 3.x. From just a few quick searches, some people recommend that people get used to it quickly as it is the future, and others say to just stay with 2.x because of the lack of ported libraries to 3.x and such.

What do you all think? Would it be a good idea to start moving over to Python 3000? Is it really necessary? Is wxPython expected to be ported over soon?

SoulMazer 26 Posting Whiz in Training

I have to say that's pretty good for your first little program. I just have one little suggestion: You don't need to do print('\n') to print a new line, you can simply use print to print a new line (correct me if I am wrong about 3.x, but this is true for 2.6).

The only other thing I can say is...expand it. First, try adding a menu option of deleting a name from the list. Next, allow the user to also enter a phone number for the name (hint: you can use a dictionary). To get a little more practice you can also try putting it into a class. It would be a very good habit to get into early.

Good work and good luck in the world of programming.

SoulMazer 26 Posting Whiz in Training

Okay, I've found my solution and I thought I would share it. Even though tkSnack cannot tell you if the stream is active or not, it does tell you how long a track is. Using that information, I used a thread to keep the elapsed time of a song (by sleeping for 0.5 seconds then updating the elapsed time).

Problem solved.

SoulMazer 26 Posting Whiz in Training

Well, thanks for the suggestion, but tkSnack does not have anything close to that.

SoulMazer 26 Posting Whiz in Training

Hi, so I'm in the process of writing a music player with a GUI. I would like to be able to print a statement after I am done playing a song. I originally through I could just get away with getting the song's length and time.sleep'ing for that long. Since my GUI has a pause button, I think just using time.sleep is out of the question, as the song and the sleep function would become out of sync. So, how would I be able to accomplish my goal? Hopefully my question is clear enough...just ask if you need more information.

By the way, I am using tkSnack as my sound library.

Thanks in advance.

SoulMazer 26 Posting Whiz in Training

My apologies, it's too late to edit my old post. I would just like to add a little more information. In simple terms, I just need to know how to download email via SMTP from a mail server.

SoulMazer 26 Posting Whiz in Training

EDIT: Hello, I need to figure out how I would download email from a Linux-based Postfix/Dovecot mail server. Is there a library that makes this relatively simple that good documentation/examples?

Thanks in advance.

SoulMazer 26 Posting Whiz in Training

Yes, you can make it work by using a tuple as the value. Example:

numbers = {}

name = "Mario"
number = "555-5555"
address = "322 Main Street"
email = "mlopez@aol.com"

numbers[name] = (number, address, email)

print numbers["Mario"][0]  # 555-5555
print numbers["Mario"][1]  # 322 Main Street
print numbers["Mario"][2]  # mlopez@aol.com
SoulMazer 26 Posting Whiz in Training

Thanks for the feedback both of you. Problem definitely solved.

SoulMazer 26 Posting Whiz in Training

Update: After a little bit of research on my own, I now have an image being displayed in a panel but I cannot add anything else. Is it possible for me to put widgets on top of this "background image"?

Code:

#!/usr/bin/python

import wx

class MyPanel(wx.Panel):
    def __init__(self, parent):
        wx.Panel.__init__(self, parent, style=wx.RAISED_BORDER)
	
        # accepted formats: .jpg .png .bmp or .gif files
        image_file = 'blah.jpg'
        bmp = wx.Bitmap(image_file)
        self.bitmap = wx.StaticBitmap(self, wx.ID_ANY, bmp, (0, 0))
	self.button1 = wx.Button(self.bitmap, id=-1, label='Button1', pos=(10, 10)) #++Gives "Segmentation Fault"
        self.SetSize((bmp.GetWidth(), bmp.GetHeight()))
        parent.Fit()

class MyFrame(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title, wx.DefaultPosition, (550, 350))
	MyPanel(self)

class MyApp(wx.App):
    def OnInit(self):
        frame = MyFrame(None, -1, 'wxCAKE')
        frame.Centre()
        frame.Show(True)
        return True

app = MyApp(0)
app.MainLoop()

Thanks again.

SoulMazer 26 Posting Whiz in Training

That is absolutely amazing Paul; this is exactly what I needed. I think you are probably one of the most helpful people in this forum. Anyways, that worked exactly how I wanted. But the one thing I would like to change around a little bit would be the color. I tried looking at the API for it and I could not figure out what it expected for the color argument in the "SetItemBackgroundColour" method. Does it want a tuple with the RGB values? The hex value? The traceback simply says it expects a "number." Also, is it possible to make the background of the main window an image? If so, how? The SetItemColumnImage method seemed quite interesting in that aspect.

Thanks again.

SoulMazer 26 Posting Whiz in Training

Hi, so I'm currently porting one of my applications (it's a media player) from Tkinter to wxPython and I am having some trouble as this is the first wx application I have attempted. I am trying to create something similar to this. However, I can't figure out the wxPython code for it. I got to the point of creating three listboxes and putting them in a sizer and that worked well; but, once I add static text above them, everything poops out. Here's a picture of what my bug looks like. Here's some code, too:

#!/usr/bin/python

import wx

class MyFrame(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title, wx.DefaultPosition, (550, 350))

        songs1 = ["Take It Easy", "Before I Forget", "Welcome", "Blitzkreig", "One"]
        songs2 = ["The Fray", "Metallica", "AC/DC", "The Eagles", "Godsmack"]
        songs3 = ["Hell Freezes Over", "Believe", "Indestructible", "All Hope is Gone", "Ten Thousand Fists"]
        
        attrpanel = wx.Panel(self, -1)
        self.songAttr = wx.StaticText(attrpanel, -1, "Songs", (170, 25), style=wx.ALIGN_CENTRE)
        self.artistAttr = wx.StaticText(attrpanel, -1, "Artists", (170, 25), style=wx.ALIGN_CENTRE)
        self.albumAttr = wx.StaticText(attrpanel, -1, "Albums", (170, 25), style=wx.ALIGN_CENTRE)
        
        attrSizer = wx.BoxSizer(wx.HORIZONTAL)
        attrSizer.Add(self.songAttr, 1)
        attrSizer.Add(self.artistAttr, 1)
        attrSizer.Add(self.albumAttr, 1)
        attrpanel.SetSizer(attrSizer)
        self.Centre()
        
        lbpanel = wx.Panel(self, -1)
        self.songBox = wx.ListBox(lbpanel, 1, wx.DefaultPosition, (170, 130), songs1, wx.LB_SINGLE)
        self.artistBox = wx.ListBox(lbpanel, 2, wx.DefaultPosition, (170, 130), songs2, wx.LB_SINGLE) #wx.DefaultPosition
        self.albumBox = wx.ListBox(lbpanel, 3, wx.DefaultPosition, (170, 130), songs3, wx.LB_SINGLE)
        
        lbSizer = wx.BoxSizer(wx.HORIZONTAL)
        lbSizer.Add(self.songBox, 1)
        lbSizer.Add(self.artistBox, 1)
        lbSizer.Add(self.albumBox, 1)
        lbpanel.SetSizer(lbSizer)
        self.Centre()
        
        
        self.songBox.SetSelection(0)
        self.artistBox.SetSelection(0)
        self.albumBox.SetSelection(0)
    
        self.Bind(wx.EVT_BUTTON, self.OnClose, id=wx.ID_CLOSE)
        self.Bind(wx.EVT_LISTBOX, self.SongSelect, id=1)
        self.Bind(wx.EVT_LISTBOX, self.ArtistSelect, id=2)
        self.Bind(wx.EVT_LISTBOX, self.AlbumSelect, id=3)

    def OnClose(self, …
SoulMazer 26 Posting Whiz in Training

Wow, thank you for the wonderful follow up. That's a great explanation of the logistics of async_chat encoding.

Thank you again.

SoulMazer 26 Posting Whiz in Training

Oh wow, well you just hit it right on the head. I had no idea that it would be so picky about the encoding. Well, thank you for all your wonderful help. Problem solved.

SoulMazer 26 Posting Whiz in Training

Sadly that doesn't seem to hint at anything either. It simply returns u'20,17,18,19,' . Is it time to just let the asynchat module win? I could just cope with the null characters if necessary.

SoulMazer 26 Posting Whiz in Training

Hmm. Well the 'allLists' variable is indeed a string, to be more exact, it's value is "17,20,18,19,". I have no idea what could be going on here, as I wrote a full fledged instant messaging program with this exact same library and never had a similar problem.

Thanks again.

SoulMazer 26 Posting Whiz in Training

Okay, removing the null characters from the string worked, except I'm still curious to why this happens and how I can prevent having to remove the null characters in the first place.

Here is my code for the server:

#!/usr/bin/python
# ConnHandler.py

import sys
import socket
import asyncore
from asynchat import async_chat
import DatabaseHandler

"""
Overview of script:

The script contains three main classes: CommandHandler, MainChannel, and MainServer. MainServer is the raw server
that sits and waits for connections from clients. Once a client is connected, they more to the "MainChannel", where
they can then send commands, which are all interpreted by CommandHandler.
"""

class CommandHandler():
    
    def __init__(self, session, data):
        'This method is called whenever the server recieves a possible command.'
        if not data.strip(): return
        databaseHandle = DatabaseHandler.Database()
        if data.strip() == "/getlists":
            allLists = databaseHandle.getLists() # Grab available list numbers from database
            session.push(allLists) # Sends a list containing the list numbers available to the client

class MainChannel(async_chat):
    
    def __init__(self, server, sock):
        async_chat.__init__(self, sock)
        self.server = server
        self.set_terminator("\r\n")
        self.data = []
        self.name = None
    
    def collect_incoming_data(self, data):
        self.data.append(data)

    def found_terminator(self):
        'When data is received, it is caught by this method and then is sent to the "CommandHandler"'
        line = ''.join(self.data)
        self.data = []
        CommandHandler(self, line)

class MainServer(asyncore.dispatcher):

    def __init__(self, port):
        asyncore.dispatcher.__init__(self)
        self.port = port
        self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
        self.bind(("", port))
        self.listen(5)
        #print "listening on port", self.port

    def handle_accept(self):
        'When a client connects to the server, they are recognized here and they are sent to the "MainChannel"'
        conn, addr = self.accept()
        MainChannel(self, …
SoulMazer 26 Posting Whiz in Training

Hi, so in essence I have two little scripts: a server side script and a client side script. My client script sends a request to the server, and the server sends a string to the client. Once I get the string back into the client, I set it to the variable myString (the value is "20,17,18,19,"). After, I run the following code:

myList = []
parts = myString.split(",")
for x in parts:
    myList.append(x)
print myList

The following is returned:

I'm not sure, but is this hex or something? And why am I getting this kind of behavior? Thanks in advance.

SoulMazer 26 Posting Whiz in Training

I'm not sure this is possible, but I have had some results with the following:

port = 80
proto = getservbyport(portnum)
print proto

I'm not quite sure why it returns "www", I would expect "http", but maybe Python has a way of translating it. You might have to research it yourself, but I hope this is a help.

joehms22 commented: This is exactly what I needed. +1