lllllIllIlllI 178 Veteran Poster
kanaku commented: I know I shouldn't be approving this much sarcasm... but LOL +2
Murtan commented: I suspect you're right, regexs are picky that way +2
well in that case 996
Hi
In one of my programs i use a wx.ToolBar, and this toolbar is meant to show a range of picutes that help the user with doing things quickly and easily. But the thing with mine is that i am using 64x64 images for the toolbar, yet when i set these on the toolbar and realize it all that turns up is a little image, one quarter of the main image, the top-left corner to be precise.
I was wondering if there was a way (probably is) to make the toolbar fit around the size of a tool.
Cheers
You could easily make a class called Book and have a list of that. It could go:
class Book(object):
def __init__(self):
self.Title = name
self.Author = author
self.ISBN = ISBN
def getAuthor(self,author):
if author == self.Author:
return self
#you could have other such methods for ISBN and Title
books = []
b1 = Book("Marlie and Me","John Grogan",1234)
b2 = Book("The Northern Lights", "Phillip Pullman",4321)
for f in books:
if f.getAuthor("Phillip Pullman"):
print f.Title
I think that works.. i haven't put it into IDLE or anything, but generally classes are a very good way to go.
There is no problem with python. What it does is that it prints the first two, tries to add to the i.third and finds it cant. Then it goes to the except: statement and that prints out, in exception
Oh and to get the reason i think it is;
except Exception,e:
print e
Well i know that some of them pop up a new windows for a raw_input/input while others ask you to enter it in the debug window down the bottom or something simmilar.
I know that for many people the pop up box is great but personally i really find it annoying after a while so i generally stick with ones that do not use pop ups.
yeah touche. That would be a lot quicker. Thanks for the tip.
I would reccomend using Wind IDE 101. Its free and great, i recently upgraded to the Personal version (about $50 AUS) and that is exellent, it has a great debugger as well as having so many customisable features.
To delete from a file i just open the file, load it all into one string, and then delete what i wanted, and then save it back into the text file again. Its not that easy at all to just edit stuff halfway through a file without knowing Exactly what is going to be there.
So borrowing a bit from sneekula:
file_in = open("myfile.txt", "r")
allfile = ''
for line in file_in:
allfile += line
allfile = allfile.replace("What you want to delete",'')
file_in.close()
file_out = open("myfile.txt",'w')
file_out.write(allfile)
file_out.close()
Kinda not on my computer at the moment so i cant test the code, but im pretty sure that should work, if not it should be close.
Hi
When using java, for almost all the time i just use java.swing for my applications that i make, yet when using other programming languages i often find that the GUI toolkit that comes bundled with the download of the Development Kit, is not quite as good as some third party libraries out there. SO i was wonding if anyone had some suggestions for more powerful/easier to use/just better libraries for making a GUI with apart from java.swing.
Cheers
Hi
I have been using java.swing for my GUI programs so far and i kinda hit a brick wall, and i think its a stupid one on my account, i cant find a way for something to load a html file to the screen using a java.swing control.
This is probably a really easy question to answer, so just a link to the API or something would be lovely.
Cheers
This smells a bit like homework. But in general, just usl Urllib to get the text from the webpage and then just use the string.count() function to get what you want.
When you ask questions like this its good to show people where you are up to in the code and not just asking for a straight out solution to your (homework?) problem.
When using a richTextCtrl on a Panel often comes up with problems such as when you press Enter\Return to make a new line nothing happens. Here is an example to show people who have no idea what problem i am taking about. Try using this code and then making a new line. It will not work.
iimport wx
import wx.richtext as rc
class MainFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, size = (120,140))
self.panel = wx.Panel(self) #Notice you cant press enter and get a new line?
self.rich = rc.RichTextCtrl(self.panel, size = (100,100))
self.Show()
app = wx.App(0)
frame = MainFrame()
app.MainLoop()
But to fix it! Just add a style of 0 to the panel!
import wx
import wx.richtext as rc
class MainFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, size = (120,140))
self.panel = wx.Panel(self, style = 0) #Yay it works
self.rich = rc.RichTextCtrl(self.panel, size = (100,100))
self.Show()
app = wx.App(0)
frame = MainFrame()
app.MainLoop()
Hope that helps anyone that had that problem, i know it stumped me for hours!
You can do a thing inside the program where you can append arguments. It goes something like:
import sys
sys.argv.append("ooh look an argument")
#now there is an argument!
Actually guys i made a programming script that does time travel! :P Its called changing the system clock! And i think that thats the best your going to do for the meantime.
For readability please wrap your code in
#your code here
it makes it a lot easier to read
Can you give us more details of the error, such as what line it was and stuff like that. See that error means your doing something like this:
s = "hello world"
s()
#error made, string object is not callable, so you cant try and call a function with it.
Ah wait, update! I found whats wrong. The colour that is green in this is not perfect green just like mk said, but its quite a way off. The green in your image is (0,128,0). That would explain why your program is not getting it.
I know that to get a list of all the pixels in the image i used image.getdata. This gave me an object and i could iterate over it, so i could go:
import Image
i = Image.open('stuff.bmp')
for pixel in i.getdata():
print pixel
Hope that helps
cheers grib that works a treat, i like the HTML making it does, thanks!
Q6 - __name__ is as it says the name of the program, when you run the program that program is given the name '__main__' as it is the main program, but other things that you import are given different names, so the reason people do this is so that if you ever want to import that program into another that the original program dosent run.
Q7 - The for keyword is used to iterate through values, so if myvalues was a list then a loop would begin where the variable item would start off being the first value of myvalues then the loop would run through, then the next value of myvalues would replace the current value of item with its own.
So for example you know a range() makes a range of numbers fror a-b. SO
for num in range(1,11):
print(num, end = "")
#it would print
#12345678910
So did you see that it ran the loop for every value in the range? cause thats what it does.
Oh delimiter is just a string, so you can have a list lets say like this:
ourList = ["hello", "World", "Its","a","nice","day]
#and then we can go
print(''.join(ourList)
#that will join every item in the list my adding them all together with nothing in the middle
#HelloWorlditsaniceday
#we can use a string variable to
delimiter = '-'
print(delimiter.join(ourList))
#this will print
#Hello-World-its-a-nice-day
!= means does not equal, so if so and so does not equal minue one …
Hi
From using java and BlueJ i have found it quite easy to make your own api using inbuilt things in BlueJ. So i was wondering if there was anything in python that would take a python program and find all of the definitions and make an API from that, in which the API would have the arguments needed as well as the docstring and other comments.
So if anyone has heard of a tool that would do this that would be lovely,
cheers
Paul
Just a thought but i think the reason nothing happens in your program is the fact that you ask nothing to happen, you make functions but you never call them, to make this work you need something to either call a function that will start it running or at least some code at the end that manages the program.
So, in summary it would be best if you perhaps had a main method that managed the program and make sure to CALL that at the end.
Q1 - Whatever you put in the inputs brackets are made into the prompt given to the user when it asks for the input.
Q2 - For a while loop, the loop goes while the value given is true, so run is equal to True so therefore it will run UNTIL the value of run is changed to False
Q3 - Continue, that keyword is used in loops, what is does is skip the rest of the loop and start on the next iteration.
Q4 - x is a global and local variable, it is in the global scope as well as in the function, you supply the value x so in the function is starts as x being 50 but then you change it to x, but that dosent change the value of x outside the function.
Q5 - In the last one it had x in the arguments needed for the function, but then in the next one you dont need to supply x because you make it global with the global x thing, now x in the function is the SAME x as x in the rest of the program.
Hope that helps
The difference between a non-keyword and a keyword is the way you supply the arguments.
a = 2
is a keyword argument, a is the keyword, 2 is the value
if you just supplied 2 then it is a non-keyword argument.
What the asterix does is that is distinguishes the non-keyword arguments and the keyword arguments. So for your function there you have one value, initial, that is set and will always be in your function, you need it to be there for the function to run. Now, when you go something like total(10,1)
there is no place that you have specified that is used to store that extra 1 so what happens to it? It is put into an array of non-keyword arguments that in your function is called numbers. So for this one: total(10,1,2,3)
The numbers 1,2 and 3 are ALL in the numbers array.
The next bit is the **keywords. This bit means that you must supply keywords as well.
Soo total(1,another = 4,anotheragain = 5)
those two arguments (another and anotheragain) have not been specified as arguements in your function, YET they have keywords, so they are stored in a Dictionary, here it is called keywords, so for the function call:
total(1,2,3,4,5,hi = 2, world = 3, test = 5)
#there would be the following values:
#initial = 1
#numbers = [2,3,4,5]
#keywords = {hi:2,world:3,test:5}
I hope you understand better now.. if not, just ask for any clarification on things you dont.
Oh and for the first question, the reason that you have to do that, is that when supplying arguments to functions they are given in order, so if you want to skip giving B a value then you have to tell …
Well i know this may be obvious, but Tkinter is all ready to be used in python 3. So anybody who uses that GUI toolkit will still be able to use it in python 30.
For a python tutorial that is good for Python 3.0 Ene Uran pointed us to this link:
http://www.swaroopch.com/notes/Python_en:Table_of_Contents
It has an up to date tutorial brought to you from the people who made dive into python. So if your confused by lots of the posts here because python does not seem to be working have a look at that link, cause you most likely are dealing with python 3.0.
mmm.. True. Hopefully it will not take that long for things to come out though. Once that has happened then i will gladly jump on the python 3.0 bandwagon. Still, well done to the guy who made that tutorial.
Thats quite an acheivement for only a short time.. maybe he wrote it a bit before and just knew when he needed from the PEPs.
By the way Ene, have you added that link to the begginging python sticky? Its sure to be useful so we dont keep getting asked why print "hello world"
is not working.
Dutch artist Job Koelewijn sure knows how to make an awesome bookcase. Behold his lemniscate bookshelf that represents the infinite power of books and learnin’
But how would you get to the books on the inside?!?
This is an example of how to use the with statement in python 3.0:
with open('test.txt') as f:
print(f.readlines())
# output >> ['test']
I know this is not that new but i think it goes through things Very well.
This is an example from the pyMedia website that will play things for you. Note that you need command line arguments for this, if you want to change this just use things like raw_inputs().
#! /bin/env python
import sys
EMULATE=0
def aplayer( name, card, rate, tt ):
import pymedia.muxer as muxer, pymedia.audio.acodec as acodec, pymedia.audio.sound as sound
import time
dm= muxer.Demuxer( str.split( name, '.' )[ -1 ].lower() )
snds= sound.getODevices()
if card not in range( len( snds ) ):
raise 'Cannot play sound to non existent device %d out of %d' % ( card+ 1, len( snds ) )
f= open( name, 'rb' )
snd= resampler= dec= None
s= f.read( 32000 )
t= 0
while len( s ):
frames= dm.parse( s )
if frames:
for fr in frames:
# Assume for now only audio streams
if dec== None:
print dm.getInfo(), dm.streams
dec= acodec.Decoder( dm.streams[ fr[ 0 ] ] )
r= dec.decode( fr[ 1 ] )
if r and r.data:
if snd== None:
print 'Opening sound with %d channels -> %s' % ( r.channels, snds[ card ][ 'name' ] )
snd= sound.Output( int( r.sample_rate* rate ), r.channels, sound.AFMT_S16_LE, card )
if rate< 1 or rate> 1:
resampler= sound.Resampler( (r.sample_rate,r.channels), (int(r.sample_rate/rate),r.channels) )
print 'Sound resampling %d->%d' % ( r.sample_rate, r.sample_rate/rate )
data= r.data
if resampler:
data= resampler.resample( data )
if EMULATE:
# Calc delay we should wait to emulate snd.play()
d= len( data )/ float( r.sample_rate* r.channels* 2 )
time.sleep( d )
if int( t+d )!= int( t ):
print 'playing: …
Just an idea but in the regular expression you look for a string that goes "group:" with a colon while in the text file you have it like "group=" so that could be screwing it up.
Write a program that gets that latest comic from your favourite webcomic.
For this you could use urllib to download the images.
Okay thats a lot clearer now, cheers everyone!
Okay.. i think i get it, but why use it? Is it just to make your code more clean?
Hi
I have been using classes for quite a while but there is still one concept yet that i havent ever quite understood and that is decorators. I have noticed Gribouillis uses them a lot so in some ways this question is directed at him. I would like to know in plain english what decorators do and how to use them, when to use them and why you use them. I found that all that i looked at in books and on the net didnt really tell me that much so any insight would be lovely.
This worked for me:
import wx
import wx.media
import os
class Events():
def __init__(self,player):
self.player = player
def pauseFile(self,event):
self.player.Pause()
class MainFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self,None,title = "Media Player")
self.panel = wx.Panel(self)
self.player = wx.media.MediaCtrl(self.panel)
self.functions = Events(self.player)
self.load = wx.Button(self.panel,wx.ID_ANY,"Load File")
self.load.Bind(wx.EVT_BUTTON,self.loadFile)
self.play = wx.Button(self.panel,wx.ID_ANY,"Play")
self.play.Bind(wx.EVT_LEFT_DOWN,self.playFile)
self.pause = wx.Button(self.panel,wx.ID_ANY,"Pause")
self.pause.Bind(wx.EVT_LEFT_DOWN,self.functions.pauseFile)
self.stop = wx.Button(self.panel,wx.ID_ANY,"Stop")
self.stop.Bind(wx.EVT_LEFT_DOWN,self.stopFile)
self.slider = wx.Slider(self.panel,wx.ID_ANY,size = (300,-1))
self.slider.Bind(wx.EVT_SLIDER,self.Seek)
self.info_name = wx.StaticText(self.panel,wx.ID_ANY,"Name:")
self.info_length = wx.StaticText(self.panel,wx.ID_ANY,"Time:")
self.info_pos = wx.StaticText(self.panel,wx.ID_ANY,"Pos:")
sizer = wx.GridBagSizer(5,5)
sizer.Add(self.slider,(1,1),(1,4))
sizer.Add(self.load,(5,1))
sizer.Add(self.play,(5,2))
sizer.Add(self.pause,(5,3))
sizer.Add(self.stop,(5,4))
sizer.Add(self.info_name,(2,1),(1,4))
sizer.Add(self.info_length,(3,1),(1,4))
sizer.Add(self.info_pos,(4,1),(1,4))
self.panel.SetSizer(sizer)
self.Show()
self.timer = wx.Timer(self)
self.Bind(wx.EVT_TIMER, self.onTimer)
self.timer.Start(100)
self.panel.SetInitialSize()
self.SetInitialSize()
def onTimer(self,event):
current = self.player.Tell()
self.info_pos.SetLabel("Pos: %i seconds" % (int(current)/1000))
self.slider.SetValue(current)
def Seek(self,event):
self.player.Seek(self.slider.GetValue())
def loadFile(self,event):
msg = wx.FileDialog(self, message = "Open a media file",
style = wx.OPEN,
wildcard = "Media Files|*.wma;*.mp3;*.avi")
if msg.ShowModal() == wx.ID_OK:
path = msg.GetPath()
self.path = path
if not self.player.Load(path):
wx.MessageBox("Unable to load this file, it is in the wrong format")
else:
self.player.Play()
def playFile(self,event):
print self.path
self.player.Play()
print self.player.Play()
self.slider.SetRange(0, self.player.Length())
self.info_length.SetLabel('length: %d seconds' % (self.player.Length()/1000))
self.info_name.SetLabel("Name: %s" % (os.path.split(self.path)[1]))
self.panel.SetInitialSize()
self.SetInitialSize()
#def pauseFile(self,event):
# self.player.Pause()
def stopFile(self,event):
self.player.Stop()
app = wx.App(False)
frame = MainFrame()
app.MainLoop()
Oh and there is a little bug i forgot about in the code. Just you have to remember at some point to add self.player to the sizer otherwise videos dont play.
There is a great module called winsound.
import winsound
winsound.PlaySound("soundFile.wav",SND_ASYNC)
raw_input()
Just make sure to change the name of the file. FOr more reference check out this page:
http://python.active-venture.com/lib/module-winsound.html
Well, Christmas eve and right now is where you find lots of TV shows trying to get into the festive season by doing a Christmas Special. Now some of these can be good... but some, just are not meant to even be christmas specials.
I thought it would be good if people posted the worst christmas special they have ever had the misfortune of watching. And perhaps the best as well, there may be some new ones added this year!
Yeah i kinda think they need some big reason for people to change to python 3.0 and i dont think they have that, i mean apart from the new print, input and with things that are in python 3.0 nothing THAT major seems to have changed, i mean some of the unpacking of variables in functions and the like have changed but in the end. Is any of this going to mean that you Want to change to python 3.0.
Personally i will be staying with python 2.5 until i find there is a sufficient reason to change, that would be a new wxPython module that is good for python 3.0 as well as some other modules such as pyGame and the like. But in the end, i really cant see why people will change apart from the fact that that is the future of python. Am i being ignorant here? I dont know. But thats just me.
Yes, for all versions 2.x-2.6 . Now that is not true when going from python 3.0 down to something like python 2.5 or 2.6 because python 3.0 is structured completley differently to python 2.5 or others. There is no raw_input() there is no print.
I heard something about a tool that they were making that you could put your python code into and it would convert it into something that could be used in python 3.0. Is that true? Is there such a tool that can do that, cause i agree with bennet. Its a pain not being able to run programs.
Another problem is that i havent found out how to work wxPython with it yet, there is no wxPython for python 3.0 yet so its all up in the air for the moment. Oh well, ill give it a few months for things to catch up.
So is this the equivalent of:
import os
class Wd(object):
def __enter__(self, directory):
self.old = os.getcwd()
os.chdir(directory)
return directory
def __exit__(self):
os.chdir(self.old)
wd = Wd('/usr/bin')
if wd:
dofilestuff()
Or am i completley missing the point of this whole thing?
Yeah, i have never actually had a look at decorators that much but from what i have seen it looks pretty good. I was having a look at the new with statement. Im having a bit of trouble getting my head around it, and also why we need it.
Hi everyone
Well, python 3.0 came out just about a week and a bit ago and i though, now people have had a chance to download it and play around with it a bit, what do you think of it? Is it better? What's the best new feature? Stuff like that. Personally i love the new print function, its great to finally see something like that in python.
Try open Ctrl+Alt+Del and going to the processes tab. Then look for any processes called "python.exe" or "pythonw.exe" then end all of those. If you have any python windows open they will shut so close everything beforehand.
Then once all processes called "python.exe" or "pythonw.exe" have ended it should work. This has worked for me before.
Ah good old SendKeys. I have written whole programs using this. Its a really great module to use. It is really simple but it has one pitfall in my mind. That is that every time that you use it NumLock is disabled. I know that dosent affect some people because they either dont use the numpad or they have laptops that dont actually have a numpad.
Here is a quick example of Sendkeys:
from SendKeys import SendKeys as sk
import time
sk('{LWIN}')
time.sleep(0.1)
sk('r')
sk('notepad.exe')
sk('{ENTER}')
time.sleep(2)
sk('hello{SPACE}world')
Could you post the code and perhaps a bit more detail of your problem. What is the input and output at the moment and stuff like that.
Write a simple calendar program. One that will remember dates that you have set. For this you would have to save it in some place.
Perhaps take a look at Pickle modules. This can be used to save instances and the like.
This program could be used very well in a GUI in fact wxPython has a specific built in object for making a calendar...