Fuse 17 Light Poster

I agree with you.

Fuse 17 Light Poster

I was about to try and help, but then I realised this is Tk. :(

Fuse 17 Light Poster

Press F5 whilst in IDLE.

If you choose to run your code outside IDLE, you'll probably see it flicker and disappear, so you'll need to use command prompt instead.

Fuse 17 Light Poster

Here's my advice: http://www.daniweb.com/forums/thread128350.html

My other advice would be Kubuntu.

But kudos for the LOGOWriter reference.

Fuse 17 Light Poster

You don't use colons or semicolons in Python, normally.

Only use colons for:
if
else
elif
def
class
for
while

And similar. Do not use a colon for import.

Fuse 17 Light Poster

IIRC, -1 is the ID of the widget. More here: http://wiki.wxpython.org/wxPython%20Style%20Guide

So you should probably replace -1 with wx.ID_ANY. I'd do that in the tutorial but I can't edit my posts after about 30 minutes after posting.

The ampersand sign is the hotkey for that menu item. Open your programme, press alt (don't hold down), then you'll see the S underlined, and you can press the S key to load that menu item.

Fuse 17 Light Poster

No problem. It's not immediately clear what it means by using event.Skip(), and I only figured it out because the focus issue seemed like what was happening with right-clicking.

I find wxPython documentation and explanations by typing into Google:

topic wxpython

Where 'topic' is what I'm looking for. E.g.:

mouse events wxpython

Gives this as the first link: http://www.wxpython.org/docs/api/wx.MouseEvent-class.html

Fuse 17 Light Poster

paulthom had an idea of adding help text to a texbox when the programme loads. The help text just explains what to type in the box and needs to disappear once the user types anything or clicks in the box. If you're interested in doing similar, or want to know how to use mouse events, go here:

http://www.daniweb.com/forums/thread128788.html

Aside from being example code that shows you how to implement such a feature, it demonstrates how funny things happen if you don't return focus to the calling widget by typing event.Skip() at the end of the mouse event's handler method.

The wxPython documentation on mouse events is a decent reference: http://www.wxpython.org/docs/api/wx.MouseEvent-class.html

Fuse 17 Light Poster

If you read the documentation for EVT_LEFT_DOWN (or UP, I suppose, but you should use DOWN really), you'll notice it says this:

EVT_LEFT_DOWN
Left mouse button down event. The handler of this event should normally call event.Skip() to allow the default processing to take place as otherwise the window under mouse wouldn't get the focus.

http://www.wxpython.org/docs/api/wx.MouseEvent-class.html

Add event.Skip() to the end of the clearin and cleartransarea methods.

Also, I never experienced it freeze up as such. Try right clicking the text box once it has 'frozen' and you'll notice you can type stuff. It's definitely due to the focus.

Fuse 17 Light Poster

Hahaha, wow. I tried this exact same thing. Actually, I thought about trying it (got as far as using SetValue for the textbox when programme loads), but decided instead to use wx.SearchCtrl.

wx.SearchCtrl is a subclass of wxTextCtrl, so it inherits all of the same stuff, but the benefit is SearchCtrl has a built-in feature for displaying greyed-out text that disappears when the users clicks in the textbox or types in it.

If you use SearchCtrl you'll need to turn off the image, which is a simple matter of calling one of its methods designed to do exactly that, IIRC.

Fuse 17 Light Poster

Don't be discouraged! The Python standard documentation is thorough, and there is much information out there for you.

In future if you're wondering if there's, say, a function to break a string up at every comma, you could try typing this in google:

string python

First result is your answer: http://docs.python.org/lib/string-methods.html

string manipulation python

Also not a bad answer: http://www.devshed.com/c/a/Python/String-Manipulation/

Here's a tutorial (actually a book which was uploaded by its author) which also covers a lot of the basic functions in Python's library: http://www.diveintopython.org/toc/index.html

Chances are if you think "wow I wish there was a basic function that could do this for me", there probably is.

Also: Die. Kittens are awesome.

Fuse 17 Light Poster

Because if you need to do a graphical game, I'm not entirely sure you have enough time to learn PyGame.

Although I suppose it'd be very easy to modify chimp.py to suit your needs.

Fuse 17 Light Poster

Maybe os.system and lpr?

Fuse 17 Light Poster
Fuse 17 Light Poster

Might I suggest going through the first few chapter of this e-book? Up to chapter 5 (file IO), at least. It covers things like closing your files after access and stuff. Good luck! :)

http://www.diveintopython.org/toc/index.html

Fuse 17 Light Poster

Phew! I thought you were going to say they don't compile. Cheers. :D

Fuse 17 Light Poster

Hi. I cleaned up your code. I didn't put it in a class, but you really should consider it.

import random

def run(money):
    global go
    try:
        bet = int(raw_input("\nPlace your bet: "))
        if bet <= money and bet > 0:
            money -= bet
            money = roll(bet, money)
            return money
        elif bet <= 0:
            go = False
            return money
        else:
            print "You can't bet that much money!"
            return money
    except ValueError:
        print "You must enter a number!"
        return money

def roll(bet, money):
    die = random.randrange(1, 100)
    if die >= 50: 
        if die >= 90:
            print "Jackpot! You rolled " + str(die)
            money = money + (bet * 5)
        else:
            print "Winner! You rolled " + str(die)
            money = money + (bet * 2)
    else:
        print "Lose! You rolled " + str(die)
    return money

def start():
    global go
    go = True
    money = 500
    try:
        highScore = int(file('highscores.txt').read())
    except:
        print "Problem loading 'highscores.txt'"
        go = False
    print "Welcome to Super Ultimate Roll-Master 3000!\nRolls are 1-100: 0-49 (Lose), 50-90 (Bet*2), 91-100 (Bet*5)\nEnter a bet of $0 to quit.\n"
    while go:
        if money > highScore:
            highScore = money
        print "Money: $" + str(money) + " High Score: $" + str(highScore)
        money = run(money)
    try:
        scoreFile = open('highscores.txt', 'w')
        scoreFile.write(str(money))
        scoreFile.close()
    except:
        print "Problem writing 'highscores.txt'"

if __name__ == "__main__":
    start()

Your error was probably a combination of little things. For example, you didn't close your files after accessing them, and you tried to compare a string to an int, like paul said, which always returned False.

Fuse 17 Light Poster

Source code for final programme and hard copy of tutorial:
http://www.mediafire.com/?fwdynnltynj

Also, you might be interested in making an executable version of your programme in Windows. I suggest you use py2exe: http://www.py2exe.org/

The executable produced is minuscule in size, but the catch is that needs like half the Python libraries as well as the full wx library to run. So most programmes you make will be at about the 15mb mark. They can easily be compressed to less than half that size, however using 7-zip, rar or zip for example.

py2exe seems to produce application that have more of a Windows 95/98/ME feel rather than an XP feel, I've found. I'm not sure if I'm missing libraries or what, but at the end of the day, it runs perfectly and looks native enough, so. But if anybody knows how to keep the XP theme it has in IDLE, let me know.

Fuse 17 Light Poster

The end result: http://img291.imageshack.us/img291/711/finalthingwy1.png

If you have any further inquiries, do a google search, read a few forum threads, and read the documentation for the method or class in question. Feel free to ask me (and others) here, too, but try and make it a last resort - you learn more through trial and error, generally.

Also, if you have any corrections, tips, or suggestions for this tutorial, please leave a comment in this thread, or on my blog: http://fuse.baywords.com/wxpython-tutorial/

Appendix

Widgets
wx.TextCtrl(parent, style=?)
Standard GUI textbox.
Styles:
wx.TE_PROCESS_ENTER
-- When the user hits the enter key, a method is called. The method called depends on the binding, as in Binding the enter key above.

wx.TE_MULTILINE
-- Textbox spans multiple lines, starting a new line when the sentence would otherwise go off-screen. Has a vertical scrollbar by default.

wx.HSCROLL
-- Create a horizontal scrollbar. I believe this works for some other widgets (hence no 'TE' prefix), but haven't tested it.

wx.TE_READONLY
-- Textbox cannot be typed in, but may still be written to by calling widgetName.SetValue(valueHere)

The are more. If you know what they are, please post them in this thread so that a moderator can update this section! I can't find them in the API... no surprise there.

wx.Button(parent, label='?')
Standard GUI button.
Styles: ?

wx.SearchCtrl(parent, style=?)
This class inherits wx.TextCtrl, so generally all …

Fuse 17 Light Poster

Message and file browsing dialogues

The widgets we need are wx.FileDialog and wx.MessageDialog. Now, because we only want it when we go to 'File' -> 'Load' on the menubar, we will actually create it in the 'Load' event method. Similarly, I will expand the event methods of 'Exit', 'Help', and 'About'.

import wx
import os

WINDOW_WIDTH = 400
WINDOW_HEIGHT = 500

class MainFrame(wx.Frame):
    """We've finally added menubars."""
    def __init__(self):
        wx.Frame.__init__(self, None, title = 'Sample GUI App',
                          pos = (200,75), size = (WINDOW_WIDTH, WINDOW_HEIGHT))

        # Menubar.  
        self.menuBar = wx.MenuBar()
        self.SetMenuBar(self.menuBar)
        self.menuFile = wx.Menu()
        self.menuInfo = wx.Menu()

        self.menuBar.Append(self.menuFile, '&File')

        self.loadItem = self.menuFile.Append(-1, '&Load')
        self.Bind(wx.EVT_MENU, self.loadEvent, self.loadItem)
       
        self.exitItem = self.menuFile.Append(-1, 'E&xit')
        self.Bind(wx.EVT_MENU, self.exitEvent, self.exitItem)
        
        self.menuBar.Append(self.menuInfo, '&Info')
        
        self.aboutItem = self.menuInfo.Append(-1, '&About')
        self.Bind(wx.EVT_MENU, self.aboutEvent, self.aboutItem)
        
        self.helpItem = self.menuInfo.Append(-1, '&Help')
        self.Bind(wx.EVT_MENU, self.helpEvent, self.helpItem)

        # Start of sizers and widgets contained within.
        self.background = wx.Panel(self)
      
        self.transferBtn = wx.Button(self.background, label = 'Transfer')
        self.transferBtn.Bind(wx.EVT_BUTTON, self.transferEvent)
        
        self.inputArea = wx.TextCtrl(self.background, style=wx.TE_PROCESS_ENTER)
        self.inputArea.Bind(wx.EVT_TEXT_ENTER, self.transferEvent)
        
        self.transferArea = wx.TextCtrl(self.background, style = wx.TE_READONLY | wx.TE_MULTILINE)

        self.horizontalBox = wx.BoxSizer()
        self.horizontalBox.Add(self.inputArea, proportion = 1, border = 0)
        self.horizontalBox.Add(self.transferBtn, proportion = 0, border = 0)

        self.verticalBox = wx.BoxSizer(wx.VERTICAL)
        self.verticalBox.Add(self.horizontalBox, proportion = 0, flag = wx.EXPAND, border = 0)
        self.verticalBox.Add(self.transferArea, proportion = 1, flag = wx.EXPAND, border = 0)

        self.background.SetSizer(self.verticalBox)
        self.Show()

    def loadEvent(self, event):
        """Create a load dialogue box, load a file onto transferArea, then destroy the load box."""
        loadBox = wx.FileDialog(self, message="Open",
                                defaultDir=os.getcwd(), defaultFile="", style=wx.OPEN)
        if loadBox.ShowModal() == wx.ID_OK: # When the user clicks 'Open', do this:
            fileName = loadBox.GetPath()
            target = open(fileName, 'rb')
            self.transferArea.SetValue(target.read())
            target.close() …
Fuse 17 Light Poster

Creating dropdown menus

import wx

WINDOW_WIDTH = 400
WINDOW_HEIGHT = 500

class MainFrame(wx.Frame):
    """We've finally added menubars."""
    def __init__(self):
        wx.Frame.__init__(self, None, title = 'Sample GUI App',
                          pos = (200,75), size = (WINDOW_WIDTH, WINDOW_HEIGHT))

        # Menubar.  
        self.menuBar = wx.MenuBar()
        self.menuFile = wx.Menu() # Create a dropdown menu for 'File'
        self.menuInfo = wx.Menu() # Create a dropdown menu for 'Info'
        self.SetMenuBar(self.menuBar) # Tell the main frame what menubar to use.

        self.menuBar.Append(self.menuFile, '&File') # Add a menu.
        
        self.loadItem = self.menuFile.Append(-1, '&Load') # Add an item to the menu.
        self.Bind(wx.EVT_MENU, self.loadEvent, self.loadItem)
        # Bind an event to the menu item. Note how for menu items the Bind format is different?
        # I specify the widget to be bound as the last parameter, not just before 'Bind', as I usually do.
        # You can use this version for any binding you do, if you want. It's necessary for menus, though.
       
        self.exitItem = self.menuFile.Append(-1, 'E&xit')
        self.Bind(wx.EVT_MENU, self.exitEvent, self.exitItem)
        
        self.menuBar.Append(self.menuInfo, '&Info')
        # Add another menu. Note how their order on the menubar depends on the order they appear in your code?
        
        self.aboutItem = self.menuInfo.Append(-1, '&About')
        self.Bind(wx.EVT_MENU, self.aboutEvent, self.aboutItem)
        
        self.helpItem = self.menuInfo.Append(-1, '&Help')
        self.Bind(wx.EVT_MENU, self.helpEvent, self.helpItem)

        # Start of sizers and widgets contained within.
        self.background = wx.Panel(self)
        
        self.transferBtn = wx.Button(self.background, label = 'Transfer')
        self.transferBtn.Bind(wx.EVT_BUTTON, self.transferEvent)
        
        self.inputArea = wx.TextCtrl(self.background, style=wx.TE_PROCESS_ENTER)
        self.inputArea.Bind(wx.EVT_TEXT_ENTER, self.transferEvent)
        
        self.transferArea = wx.TextCtrl(self.background, style = wx.TE_READONLY | wx.TE_MULTILINE)

        self.horizontalBox = wx.BoxSizer()
        self.horizontalBox.Add(self.inputArea, proportion = 1, border = 0)
        self.horizontalBox.Add(self.transferBtn, proportion = 0, border = 0)

        self.verticalBox = wx.BoxSizer(wx.VERTICAL)
        self.verticalBox.Add(self.horizontalBox, proportion = 0, flag = wx.EXPAND, border …
Fuse 17 Light Poster

Event handling

import wx

WINDOW_WIDTH = 400
WINDOW_HEIGHT = 500

class MainFrame(wx.Frame):
    """A working programme! Event handling, binding, methods, the lot."""
    def __init__(self):
        wx.Frame.__init__(self, None, title = 'Sample GUI App',
                          pos = (200,75), size = (WINDOW_WIDTH, WINDOW_HEIGHT))
        
        self.background = wx.Panel(self)

        self.loadBtn = wx.Button(self.background, label = 'Load')
        self.loadBtn.Bind(wx.EVT_BUTTON, self.loadEvent)
        
        self.transferBtn = wx.Button(self.background, label = 'Transfer')
        self.transferBtn.Bind(wx.EVT_BUTTON, self.transferEvent)
        
        self.inputArea = wx.TextCtrl(self.background)
        self.transferArea = wx.TextCtrl(self.background, style = wx.TE_READONLY | wx.TE_MULTILINE)

        self.horizontalBox = wx.BoxSizer()
        self.horizontalBox.Add(self.inputArea, proportion = 1, border = 0)
        self.horizontalBox.Add(self.transferBtn, proportion = 0, border = 0)
        self.horizontalBox.Add(self.loadBtn, proportion = 0, border = 0)

        self.verticalBox = wx.BoxSizer(wx.VERTICAL)
        self.verticalBox.Add(self.horizontalBox, proportion = 0, flag = wx.EXPAND, border = 0)
        self.verticalBox.Add(self.transferArea, proportion = 1, flag = wx.EXPAND, border = 0)

        self.background.SetSizer(self.verticalBox)
        self.Show()

    def loadEvent(self, event):
        fileContents = open(self.inputArea.GetValue(), 'rb')
        self.transferArea.SetValue(fileContents.read())
        fileContents.close()

    def transferEvent(self, event):
        self.transferArea.SetValue(self.inputArea.GetValue())
    
app = wx.App(redirect=False)
window = MainFrame()
app.MainLoop()

I added two bind commands, one for each button, and two methods to the class. That's it. Have fun fiddling with your own methods!

(The programme transfer whatever you type into the small box, inputArea, into the larger box, transferArea once you press 'Transfer'. Alternatively, you can type a file location into the inputArea and press load and it will load that file into the transferArea.)

Binding the enter key

Maybe you'd like to know how to make a textbox call a certain method when somebody hits the enter key? Add the style wx.TE_PROCESS_ENTER to the textbox's style section, then add a new binding below the textbox: textboxWidget.Bind(wx.EVT_TEXT_ENTER, functionNameHere), like …

Fuse 17 Light Poster

Putting it in classes

One more thing before event handling... let's make our code more shall we say 'standard':

import wx

# Declare constants in capitals and as global variables at the start of your code
# This makes it much easier to change them later, especially if they are used often.
# It also indicates they are values that won't change throughout the programme's execution.

WINDOW_WIDTH = 400
WINDOW_HEIGHT = 500

class MainFrame(wx.Frame):

    def __init__(self):
        wx.Frame.__init__(self, None, title = 'Sample GUI App',
                          pos = (200,75), size = (WINDOW_WIDTH, WINDOW_HEIGHT))
        
        self.background = wx.Panel(self)

        self.loadBtn = wx.Button(self.background, label = 'Load')
        self.transferBtn = wx.Button(self.background, label = 'Transfer')
        self.inputArea = wx.TextCtrl(self.background)
        self.transferArea = wx.TextCtrl(self.background, style = wx.TE_READONLY | wx.TE_MULTILINE)

        self.horizontalBox = wx.BoxSizer()
        self.horizontalBox.Add(self.inputArea, proportion = 1, border = 0)
        self.horizontalBox.Add(self.transferBtn, proportion = 0, border = 0)
        self.horizontalBox.Add(self.loadBtn, proportion = 0, border = 0)

        self.verticalBox = wx.BoxSizer(wx.VERTICAL)
        self.verticalBox.Add(self.horizontalBox, proportion = 0, flag = wx.EXPAND, border = 0)
        self.verticalBox.Add(self.transferArea, proportion = 1, flag = wx.EXPAND, border = 0)

        self.background.SetSizer(self.verticalBox)
        self.Show()
    
app = wx.App(redirect=False)
window = MainFrame()
app.MainLoop()

I have thrown it all in a class. That's about it. Look over it, compile it, run it, understand it, etc. Note how you can always use classes to seperate parts of your programme. Generally whenever you have a new panel/frame/window, you should put it in its own class. Now on to the good stuff.

Fuse 17 Light Poster

Sizers

import wx

"""Example with sizers for dynamic resizing."""

app = wx.App(redirect=False)

window = wx.Frame(None, title = 'Sample GUI App',
                  pos = (100,100), size = (400,500))
background = wx.Panel(window)

loadBtn = wx.Button(background, label = 'Load')
transferBtn = wx.Button(background, label = 'Transfer')
inputArea = wx.TextCtrl(background)
transferArea = wx.TextCtrl(background, style = wx.TE_READONLY | wx.TE_MULTILINE)

horizontalBox = wx.BoxSizer()
horizontalBox.Add(inputArea, proportion = 1, border = 0)
horizontalBox.Add(transferBtn, proportion = 0, border = 0)
horizontalBox.Add(loadBtn, proportion = 0, border = 0)

verticalBox = wx.BoxSizer(wx.VERTICAL)
verticalBox.Add(horizontalBox, proportion = 0, flag = wx.EXPAND, border = 0)
verticalBox.Add(transferArea, proportion = 1, flag = wx.EXPAND, border = 0)

background.SetSizer(verticalBox)
window.Show()
app.MainLoop()

Notice how the 'tree' is preserved? You can eventually trace the buttons and text box back to the parent window through the background widget.

Remember, anything starting with a lower case letter tends to be an arbitrary variable name which you can rename to whatever you want. It is the things with capitals at the start that are important. Conventionally (at least in C++, Java and Haskell), you name variables and functions: thisIsAVariable, and classes: ThisIsAClass. So you could rename 'window' and 'background' to anything you wanted. Same applies to the widget names.

Have a fiddle with that. Sizers are a bit complex at first but you should use them instead of statically defining the size and start co-ords. Note the hierarchy: horizontalBox is a child of verticalBox. Position in the programme depends on location in the code, as you'll see below.

Note I …

TranquilWaters commented: This starting guide in wxPython is great :-) +0
Fuse 17 Light Poster

Well, here's the tutorial like you asked for. I've expanded on it quite a bit. Could people please read over it, in case I've made mistakes? There's a better version at my blog because it features screenshots. Link: http://fuse.baywords.com/wxpython-tutorial/

Tutorial: GUI programming with wxPython

Index
Introduction
Start
Sizers
Putting it in classes
Event handling
Binding the enter key
Creating dropdown menus
Message and file browsing dialogues
Appendix

Introduction
Hi there! So you've made a few scripts in Python. They work really well, you maybe know your way around file IO, string manipulation, and list splicing (and heck maybe even regular expressions and other cool stuff)... but you're thinking "Is that it? Surely there's more to Python." So this is it: GUI programming. Here I explain how to make the move from the command line to full-blown graphical programmes like you see in KDE, Mac or Windows.

GUI programming is fast, self-contained, and simple. So you can code your functions first, or your GUI first - it's up to you. GUI programming is like LEGO: you have a few core blocks and you build everything else from those blocks. There's not much you can't build, and once you understand how those few core blocks work, where they fit, GUI programming will become second nature. There are numerous GUI packages available to use with Python. Tkinter comes …

lllllIllIlllI commented: Really really good tutorial +1
Lardmeister commented: nicely done, easy to understand +4
sneekula commented: You make wxPython sound very interesting +4
Fuse 17 Light Poster

I think so, too. Up to vegasat.

Fuse 17 Light Poster

I think you have to write it this way:
patternMatching(r"The|fox", 'The little brown fox')

Thanks! That would normally work. Unfortunately, that's not possible. This programme is designed to accept a user's own regular expression, so I have to accept the full range of regular expression syntax. I've got this solution so far, but I figured surely something more elegant would exist.

def patternMatching(self, event):
    matchList = re.findall(self.patternArea.GetValue(), self.inputArea.GetValue())
    for n in range(0, len(matchList)):
        if type(matchList[n]) == type(''):
            matchList[n] = (matchList[n],)
    outputString = ''
    for tupleElement in matchList:
        outputString += '\n'.join(['%s' % stringElement for stringElement in tupleElement])
    self.outputArea.SetValue(outputString)

Slate: Yes, but that's counter-intuitive. If there's one group you'll be iterating over a string, but if there's more than one it will be a tuple. Kind of un-Pythonic, no? It would make much more sense for the case of one group to be a 1-tuple.

Fuse 17 Light Poster

Actually, it it is looking, acting and sounding like a duck. It's a 1-tuple, so it's still a tuple. Python seems to think a 1-tuple is better expressed simply as the element within the 1-tuple, however, which causes this problem.

Fuse 17 Light Poster

I have a problem guys. It's due to duck typing. Now I expected to run into something like this sooner or later, but I can't help but feel there's a better solution.

import re
def patternMatching(pattern, string):  
    matchList = re.findall(pattern, string)
    print '\n'.join(['%s' % v for v in matchList])

If you run that function as patternMatching(r'The (fox)', 'The fox'), it gives you 'fox', right? Because matchList is .

But what if you run it as patternMatching(r'(The) (fox)', 'The fox')? You get an error. Because matchList is [('The','fox')].

Duck typing is messing with my types, so the print function won't work.

Traceback (most recent call last):
  File "<pyshell#52>", line 1, in <module>
    print '\n'.join(['%s' % v for v in matchList])
TypeError: not all arguments converted during string formatting

What's a programmer to do? My patch solution is to check the type of the first element and then do two cases. But that won't hold if I get something like [('hello','bye'),'hello']... which I'm not sure I ever will, but the point remains.

Fuse 17 Light Poster

The best way to learn is to teach a subject. I have enjoyed your presentation of wxPython too.

Compared to Tkinter, wxPython's power is in its clever widgets, a more pythonic approach.

I hear you! And I'm not sure what this mysterious 'Pythonic' coding style is, but I suspect it is generally how I intuitively code, due to my first programming experiences being Java's pure OO paradigm and Haskell's pure functional paradigm.

As a side note, I highly recommend Haskell to everybody (especially anybody who enjoys Python). There's even a wxHaskell implementation, which mainly uses monads to emulate imperative programming. Not the best language to code in, but an invaluable language to learn to improve your programming ability and style. As a bonus, Haskell is white-space sensitive like Python, and has a beautiful standard library (better than or equal to Python's in my opinion), so it is understandably easy to learn once you adjust to the functional paradigm.

In fact I have a feeling Python was influenced by Haskell or something similar, because it has white-space sensitivity, list comprehensions, lambda functions, lists, tuples, strict typing, an interpreter, etc. I learnt from an excellent book: 'Haskell: The Craft of Functional Programming', if anyone's interested. In fact, I'd probably describe Python as Haskell + Java.

Fuse 17 Light Poster

Maybe it's not so clear what I wrote. I have a file that contains three columns -two with names and third with numbers. I just want to sort lines according to numbers.

Yes, but as wooee says (though I don't really understand his code), you need to split into a list before you can sort it. I'd personally split it at '\n' and then again at ' ', so you have a list of lists, and can sort the data according to column 1, 2, or 3 based on array indexes. :)

Actually, I think wooee is doing exactly that. Read more here: http://wiki.python.org/moin/HowTo/Sorting

Fuse 17 Light Poster

We coved this a few threads down:

http://www.daniweb.com/forums/thread127918.html

Hope that helps.

Fuse 17 Light Poster

I discovered what the problem was, and I will not (can't) fix it. It is the chr(0) character.

http://python-forum.org/pythonforum/viewtopic.php?f=3&t=8298&sid=074fe5da17f88c7b625d5792f9bff2ac#p38443

Fuse 17 Light Poster

Sure thing! Glad you liked it.

I'll clean it up tomorrow (or soonish) as there are a few errors and typos, as well as elaborate on some points (such as using multiple horizontal box sizers for more complex widget positioning). I'm also teaching myself about some other widgets, so I'll add them if I feel they could do with explaining.

Fuse 17 Light Poster

Why not just create checkboxes, hide them, and then on the event of a tree node expansion, show the corresponding checkboxes?

Fuse 17 Light Poster

I just started messing with Python, and was having a great time with entering Tkinter GUI commands into the Python shell (ActivePython 2.5).
Its fun entering commands one at a time and seeing components appear real-time (instead of normal process of having to compile the whole thing first).

Anyway, I was wondering if there was a way to paste multiple lines of source code (at once).

Also: Is there a function that causes a string to be interpreted as a command?

I suggest the standard IDLE instead. I found ActivePython lacking in features (dedent region, indent region, comment region, uncomment region) yet containing no new (useful) ones.

As for pasting multiple lines: well, you can paste multiple lines, but it only seems to evaluate the first one.

What you can instead do is nest those multiple lines in a function, and then paste it.

def test():
  line1 = 'bah'
  line2 = 'foo'
  print line2 + line1

now type test() for the result 'foobah'

whereas

line1 = 'bah'
line2 = 'foo'
print line2 + line1

would only evaluate line1 = 'bah'

This is only marginally easier than creating an actual script, since you get to avoid creating a file just for a test.

Re using strings as commands... what's the context?

Oh, and I highly recommend wxPython over Tkinter. Much more powerful, intuitive and easy to use, IMHO. Also newer: http://www.wxpython.org/quotes.php

Note the words by Eric …

Fuse 17 Light Poster

Care to elaborate... a lot? I mean it'd help if you mentioned what GUI module you're using, for a start.

Fuse 17 Light Poster

Maybe you can do something fancy with JPython?

Yep: http://www.jython.org/applets/index.html

You'll need to do some fiddling, but I'm guessing it's much easier than re-writing your code in Java.

A fun example: http://www.jython.org/applets/coordinates.html

Fuse 17 Light Poster

Cheers mate! That's ace.

Sorry if the OP is a jumble; I haven't had sleep. (I repeated myself about the image grabber script.)

Fuse 17 Light Poster

You mean like a Java applet? I'm not sure, but I think if you want to do that you need to learn, well, Java.

It's no small task and Java is specifically designed for the job (among other things) due to its common-place virtual machine and such.

Fuse 17 Light Poster

I am trying to add user input using the raw_input function to string url_orig. I am attempting to replace the spaces with +'s to make a 'google search'. the replace function works fine in IDE but not when I excecute the program. Any help will be appreciated

url_orig = 'http://www.google.com/search?hl=en&q='
url_add1 = ''
s.replace(' ', '+')
print s

Erm. Do you have a GUI? If so use a text box. If not, then you'll call the function from command line, right? So you can assume they'll enter input at command line. I don't know how to do input otherwise.

I don't see why you want to fiddle with +'s and spaces? The end? Please define your problem more clearly. It would help if you actually, you know, gave us your full code. I have no clue what s is for example.

BTW: unless you pretend you are Opera or Firefox or something, google won't let you perform a search.

Edit: I think I get you. Well you could try:

s = '+'.join((s.split(' ')))

I've never used replace() so I couldn't tell you what's wrong there.

I just tried replace. It works fine for me. I doubt your code worked for you at all, TBH, since you forgot to assign the replacement:
s = s.replace(' ', '+')

Fuse 17 Light Poster

Np. It would be wise to make sure you understand what I wrote and not just copy that code straight into your programme, though.

Fuse 17 Light Poster

Then let me write one for you:

import wx

app = wx.App() # create a wx application

window = wx.Frame(None, title = 'Sample GUI App') # create a window
btn = wx.Button(window) 
# create a button 'widget' on the window - note how the button receives the window. This creates a tree-like structure where the window is the parent node and anything else like buttons are child nodes.

window.Show() # make the frame and button visible
app.MainLoop() # keep things going

This makes a window. It then puts a button on the window. Yes, the button takes up the whole window. Have a read, understand it, fiddle if you can, then go on. Please compile this code now to confirm it runs. Onwards:

import wx

app = wx.App()

window = wx.Frame(None, title = 'Sample GUI App',
                  pos = (100,100), size = (400,500))
helloBtn = wx.Button(window, label = 'Hello',
                pos = (400 - 60 - 15, 10), size = (60,25))
byeBtn = wx.Button(window, label = 'Bye',
                pos = (400 - 120 - 15, 10), size = (60,25))
printArea = wx.TextCtrl(window,
                        pos = (10, 10), size = (400 - 120 - 15 - 10, 25),
                        style = wx.TE_READONLY)
window.Show()
app.MainLoop()

Compile and run this code first. Now look at the placement of widgets and what they are. Notice wx.TextCtrl is a text box. It's quite flexible - allowing multiline text with scroll bars, read only mode, write mode, etc. I've set it to read only for what I am about …

vegaseat commented: great intro to wxPython +8
Fuse 17 Light Poster

Use regular expressions.

Or use the split method.

I'd use regexp's because you've got both \t AND \n. Though I suppose that's a lot of extra overhead (someone tell me? I'm not sure how efficient regexps are compared to say string manipulation methods), so it's probably better to just go:

lineList = line.split('\t')
lineList = lineList[:-1] + [lineList[-1].split('\n')[0]]

Or in more explicit terms:

Split the list at every tab. Now take the last element of the new-formed list, and split it at the newline '\n'. This will give you a list with two elements: a number and a newline. Take the first element of the sublist and concatenate it to the original list of numbers up to it's last element. Id est:

line = '0.00\t2.869e-12\t7.715e-08\t0.000e+00\t0.000e+00\n'
lineList = line.split('\t') 
# this gives you ['0.00', '2.869e-12', '7.715e-08', '0.000e+00', '0.000e+00\n']
temp = lineList[0]
# this gives you '0.000e+00\n'
tempList = temp.split('\n')
# this gives you ['0.000e+00', '']
tempList = [tempList[0]]
# this gives you ['0.000e+00']
lineList = lineList[:-1]
# this gives you ['0.00', '2.869e-12', '7.715e-08', '0.000e+00']
lineList += tempList
# this gives you the final result of ['0.00', '2.869e-12', '7.715e-08', '0.000e+00', '0.000e+00']
Fuse 17 Light Poster

I learnt wxPython yesterday. I tried Tkinter at first, but disliked it. Here's a summary of why: http://www.wxpython.org/quotes.php

It's really easy to learn and understand. The trouble is there's little sample code and many tutorials on it are out of date because it seems to change a fair bit each revision.

I recommend this post here as a good reference: http://www.daniweb.com/forums/post335474-3.html

You might also be interested in my application which is fairly simple but a good example of a working wxPython app: http://www.daniweb.com/forums/thread127935.html

Fuse 17 Light Poster

Hi there. I'm new to Python. I started learning it 3 days ago. I've figured out everything by myself so far, but this is stumping me:

Whenever I load a file such as a html document or a text file, it loads fine. But when I load this gif or png file (probably many other formats, too), it only loads the first few bits of it. It happens in both urlopen() and normal file open().

E.g. http://www.majhost.com/gallery/Lijik/Star-Wars-Figures-1/ewjclay.png

Only loads:

‰PNG

Here is my code. It's a programme I made (the first one I've ever made, actually - in the past I always lost interest half-way) to help people learn regular expressions (because when I was learning them yesterday I found it a hassle using the Python interpreter). It's helpful for anybody using regexps, though, I reckon, because it's a great testing ground. The other programme I'm making downloads all the images from a website by applying a regexp to the HTML code and then forming absolute links to the images and putting them in a set to remove duplicates. It's currently just a script but tomorrow I'll make it a programme where you can preview the images and select which ones to save to your computer.

Also, any comments on my coding style - what I'm doing wrong, what I'm doing inefficiently, etc, would be appreciated.

Thanks!

import urllib
import re
import wx

# Welcome to the Regular Express!
# Code …