You could display the path your program gets from the user in a Tkinter Label positioned below the buttons?
vegaseat commented: Very nice solution +8
You could display the path your program gets from the user in a Tkinter Label positioned below the buttons?
what do you mean when you ask how to make the program show the paths to the selected folder and file.
Do you want to show the file's contents, show an explorer window of the file's location or some sort of tree view of the file?
there must be something else going on. When you make a copy of a list list2 = list1[:]
it fills list2 with list1's values, but when you change either list1 or list2, the change isn't mirrored so list1 would stay the same if list2 was changed.
Are you sure your not doing something else incorrect? If you can, post the section of your code were the checker lists are used and changed etc then someone might be able to see if anything else is happening
# This is meant to draw Start and Stop buttons and a label
# The Start button should start a loop in which the label
# is configured to change colour and text.
# At each pass through the loop the variable self.stop is checked:
# if True the loop should terminate.
# The Stop button should terminate the loop by setting the
# variable self.stop to True.
# I have two problems:
# 1. the Stop button does not interrupt the loop
# 2. the label only shows its reconfigured state at the end of the loop
# Please, what are my misconceptions about how this works, and what
# do I need to do to make it do what I expected?
# What I am really trying to do is show an animation but have a button
# to enable users to stop it.
from Tkinter import *
import time
from random import choice
COLORS = ['red','green','blue','orange','brown','black','white','purple','violet']
class SGWidget(Frame):
def __init__(self, parent=None):
Frame.__init__(self, parent)
self.top_frame = Frame(bg='green')
self.top_frame.grid()
self.top_frame.update_idletasks()
self.makeToolbar()
self.label = Label(self.top_frame,
text = 'Text',bg='orange')
self.label.grid()
def makeToolbar(self):
self.toolbar_text = ['Start','Stop']
self.toolbar_length = len(self.toolbar_text)
self.toolbar_buttons = [None] * self.toolbar_length
for toolbar_index in range(self.toolbar_length):
text = self.toolbar_text[toolbar_index]
bg = 'yellow'
button_id = Button(self.top_frame,
text=text,
background=bg)
button_id.grid(row=0, column=toolbar_index)
self.toolbar_buttons[toolbar_index] = button_id
def toolbar_button_handler(event, self=self, button=toolbar_index):
return self.service_toolbar(button)
button_id.bind("<Button-1>", toolbar_button_handler)
def service_toolbar(self, toolbar_index):
if toolbar_index == 0:
self.stop = False
print self.stop
self.blink()
if toolbar_index == 1:
self.stop = True
print self.stop
def blink(self):
if not self.stop:
print 'looping',self.stop …
excellent, happy coding
You don't need to get a fileobject though. As solsteel pointed out, the csv module doesn't need a fileobject, it just needs something to iterate through, so if you split the self[filename] string by every newline ('\n') then you will end up with a list of lines which the csv reader module can parse.
Solsteel's example looks perfect.
csv.reader(str(self[filename]).split('\n'))
well as far as i can see, whatever resides within self[filename]
is clearly not a valid filepath.
There was a sort of hint to what it might contain in the second error.
[IOError] of [Errno 36] File name too long: 'ProjCat,RefNum,ProjTitle,MemberName,ProjDeadline,ProjGrade\nI,0001,"Medical Research in XXX Field,2007","Gary,Susan",20.05.07,80\nR,0023,Grid Computing in today era,"Henry Williams,Tulali Mark",04-May-07,--NA--........'
ProjCat,RefNum,ProjTitle,.... etc etc, that is not a filepath.
the open function needs a filepath string like 'textfile.txt' and you appear to be passing a very very long string of words, comma's etc.
You should read the documentation for the csv module, and i think Zope is confusing things. are you trying to parse a file thats stored somewhere (has a filename .csv etc)? or are you reading the csv data from zope. If it's from zope then i don't think the open() command is what you want.
Open opens a file and returns a fileobject, which csv.reader() then parses, if self[filename]
isn't a file then it will not work.
def function(*args):
print type(args)
print args
function('arg1', 'arg2', 'arg3')
output
<type 'tuple'>
('arg1', 'arg2', 'arg3')
If you need a list: args = list(args)
You should definitely use tkinters .after() function, it enters a local event loop which means it doesn't block your program.
def blink(self):
if not self.stop: # check self.stop is false before proceeding
print 'looping',self.stop
self.label.configure(bg=choice(COLORS))
self.label.update_idletasks()
self.after(100, self.blink) # after 100 ms, call function self.blink
choice is a function imported from random,
COLORS is a list containing colors, eg: ['green','red','blue']
etc
Hope that helps
n = float(2)
m = float(3)
print n/m
Or
n = 2.0
m = 3.0
print n/m
Hope that helps.
Well you could just use a Thread object to do the counting for you and then in your main program everytime the user enters a key, you just call a function of the Thread object counting that returns it's current value.
The example below might help.
# counterTest.py, a1eio
import threading
# create a thread object that will do the counting in a separate thread
class counter(threading.Thread):
def __init__(self, value, increment):
threading.Thread.__init__(self) # init the thread
self.value = value # initial value
self.increment = increment # amount to increment
self.alive = False # controls the while loop in the run command
def run(self): # this is the main function that will run in a separate thread
self.alive = True
while self.alive:
self.value += self.increment # do the counting
def peek(self): # return the current value
return self.value
def finish(self): # close the thread, return final value
self.alive = False # stop the while loop in 'run'
return self.value # return value
def Main():
# create separate instances of the counter
counterA = counter(1, 1) #initial value, increment
counterB = counter(1, 2) #initial value, increment
counterC = counter(1, 3) #initial value, increment
# start each counter
counterA.start()
counterB.start()
counterC.start()
print "Enter A, B, or C to view counters\nEnter Q to quit"
while True:
Input = raw_input("> ").upper() # get input
if Input == 'A':
print 'CounterA: ', counterA.peek() # print counterA's value
elif Input == 'B':
print 'CounterB: ', counterB.peek() # print counterB's value
elif Input == 'C':
print …
did you define gold?
gold = gold + 5
if 'gold' is not defined before that statement then it doesn't know what to add 5 onto.
Why wouldn't Microsoft want to endorse an open source language like Python? What would they lose?
competition?
easier for a giant like MS to keep python in 'check' than allow another powerful open source language like python which could result in a drop in sales if software becomes easier to develop and cheaper/free to buy??
1.1 What is Jython?
Jython implements the Python programming language on the Java(tm) Platform. It consists of a compiler to compile Python source code down to Java bytecodes which can run directly on a JVM, a set of support libraries which are used by the compiled Java bytecodes, and extra support to make it trivial to use Java packages from within Jython.
java is just like python, it's just that java's virtual machine is a hell of a lot more widely spread, known and used than pythons interpretter.
why do you think Jython is so good at what it does.
hahahaha!!!! i was typing away and hit enter without even pasting the link in :)
terribly sorry
i'm not sure, i havn't used the double underscore methods much (if at all) but as far as i am aware, the __str__ method links with the 'print' keyword, so if print object is called then that objects __str__ method would be called and the result (returned value) of that would be displayed if it was a string, otherwise it returns an error.
So i'm not really sure if there's a method to return a list.
I am currently looking through the following page to see what kinda things you can do. You will probably find it useful also, although sometimes the documentation is a bit hard to understand (i think so anyway).
hope that helps
a1eio
well, if you want to be able to 'print' the kangaroo instance in your case your trying to print 'kanga' then just make the '__str__' method return a string and that string will get printed:
...
...
def __str__(self):
return str(self.pouch)
....
....
kanga = Kangaroo()
roo = Kangaroo()
kanga + roo
print kanga
i get:
>>>
[10]
[100]
[10, 100]
>>>
hope that helps
a1eio
not sure what you mean exactly, but why are you creating a temporary instance of Kangaroo in the put in pouch function?
I thought you meant you wanted roo's pouch added into kanga's pouch?
if thats the case then your code is fine, except you need to define pouch in init.
class Kangaroo:
def __init__(self, contents=10):
self.pouch = []
self.pouch.append(contents)
...
...
...
def put_in_pouch(self, other)
self.pouch.extend(other.pouch)
master = Kangaroo('master')
for i in range(10):
master + Kangaroo(i)
print master.pouch
my result is:
>>>
['master']
[0]
[1]
[2]
[3]
[4]
[5]
[6]
[7]
[8]
[9]
['master', 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>
hope that helps
a1eio
hehe, nicely put vega, i totally forgot about that beautiful aspect of python
python has defiantly spioled me!
i hate the look of other languages even tho i'd love to learn them.. whenever i try.. i end up going back to python just cause it's so much clearer and quicker to make things.
i just wish it was a bit easier to create standalone programs that don't need the interpreter running. (i've tried py2exe but i just can't get my head round it)
not sure what you mean by adding fonts,
but when you create a font object, you can specify a pygame font, or a path to a custom font of your choice.
font1 = pygame.font.Font("C:\customfont.ttf", 12)
it's never too late to learn python :)
awesome language, you'll pick it up quick and it beats VB (in my opinion)
lol pygame is fun, give it a go.. hardly industry standard top notch gaming, but you can make some very interesting games :)
there's nothing wrong with your program from what i can see, apart from it printing false positives, everything else is doing as it should, you have a loop that will find all possible values... unless you leave it after the first result.
Hi,
i might be missing something, but from what i understand your program, gets an int from the user, validates it, then it enters a for loop and checks each number (p) of the loops range, to see if its prime and if the user's number minus p, is prime. If it is then it prints the results, and carries on till the end of the loop. If you only want one result for each number then break after the first result:
if is_prime(p) and is_prime(n - p):
print "="*40,"\nFound two prime numbers that sum to",n,"!"
print n, '= %d + %d' % (p, n - p),"\n","="*40
break
However i get the feeling i'm missing some important thing about prime numbers... the solution seems too simple hehehe
yea, ditch the printing and append it to a list and it'll be almost instant. :)
I personally always use the root.destroy() method, it seems to work best and I've never had any problems with it.
Hmm that's odd.
A single '.' represents the current working path. So you should in theory use that, e.g:
f = file("./SubFolder/test.txt", "r")
f.read()
the above code would open a file called test.txt in the SubFolder, which would be located in the same folder as the 'current working directory' (which SHOULD be where the script is).
So the full path for test.txt could be something like:
"Python/SubFolder/"
But I'm not sure why the previous example didn't work.
Anyway, try using a . in your path, that may work.
hope that helps
alex
P.S
By the way, a single dot (.) means the current folder,
a double dot (..) would go back one folder so you could use "../../" to go back two folders.
EDIT:
One more thing, http://www.bembry.org/technology/python/notes/lesson_12.php
has some pretty good info basic file/folder manipulation.
I'm not sure if I'm reading your question correctly, but if you want to open a file that's in the SAME place as your .py script that opens the file, you don't need to set any form of path name. You just type in the name of the file on it's own, for example:
f = file("test.txt","r")
print f.read()
if you saved that into a folder, as long as the file: "test.txt" is in the same folder then it'd run fine.
As for your second question, i don't really know much about wxpython but as far as i was aware python programs were all interpreted, meaning they cant be made into 'stand-alone' .exe/.app programs, the only work around i know of is py2exe. If you used that then no the user wouldn't need to have python or wxpython installed, the downside to py2exe however is that it bundles all the dependencies together which means you might end up with a very large program folder.
Hope this helps
http://bembry.org/technology/python/index.php
Has a whole quick tutorial and it has notes on all the main topics it covers, so you can read it, or use it as a reference, i found the Tkinter section wickedly useful as a starter into gui stuff, it also has some exercises.
hmm, are you using 'len' as a variable anywhere else in your program?
Check to see if you are using 'len' as a variable in your program, because thats where i get the error:
dic = {1:1,2:2,3:3,4:4}
print len(dic)
def main():
print len(dic)
len = len(dic)
if __name__ == '__main__':
main()
and the output:
>>>
4Traceback (most recent call last):
File "C:/Python25/testDICTS.py", line 10, in <module>
main()
File "C:/Python25/testDICTS.py", line 6, in main
print len(dic)
UnboundLocalError: local variable 'len' referenced before assignment
Tis a funny error though, i never did work it out, i just changed my code till i didn't get it, hehe if that doesn't work then i don't know, sorry
happy coding
a1eio
where you have the 'try' and 'except' section of your code, your checking to see if there is a NameError, that means, if there is a NameError, it will catch it, however, it will not catch any others. If you don't specify a particular error to catch, then it will check for all errors.
in simple terms, just take NameError out of the except part, so your left with simply:
except:
...
however, if you want to return specific responses acording to specific errors you could have something along the lines of:
try:
...
except NameError:
print "Please enter a number."
except SyntaxError:
print "You must enter something"
except:
print "Stop screwing about and just enter number!"
but that above isn't probably needed, as the user is only entering a number. so on except: should do it all.
Sweet man!, thats wicked. Nevermind the 'shortcuts' it works like a beaut'.
One thing though, when you enter large armies (eg: 10 v 10) it keeps running the simulation until the end, where it then shows you the final outcome, you could (if you wanted) put in a simple line:
raw_input("Hit Enter To Continue")
this would act as a 'pause' (very much like the one you have at the VERY end of your program) allowing the reader to read that particular battle then move on to the next when ready. All you would have to do is put it at the begining (or end) of the main 'while True' loop.
Great job though :)
glad you liked em, lists are wonderful things, lots of things can be done with them. Another great thing i love about lists is something called list comprehension.
List comprehension works in the following way:
[expression for item in sequence (if condition [I]not necesary[/I])] # Thats the rough outline
# Here's a simple example
>>> [1 for num in range(5)]
[1, 1, 1, 1, 1]
First i'm telling python to put '1' in the list, then i tell python it's going to keep putting '1' inside it untill the 'for num in range(5)' stops looping.
Here's an example that fits your code:
>>> alist = [random.randint(1,6) for num in range(3)]
>>> dlist = [random.randint(1,6) for num in range(2)]
>>> print alist
[4, 6, 1]
>>> print dlist
[3, 5]
In the example above, python understands that random.randint(1,6) is going to be placed in the list 3 times (3 times, because the for loop is looping 3 times; range(3))
list comprehension, simply 'compreses' loops eg if you wanted to do the above without using list comprehension, you would simply use a for loop:
>>> alist = []
>>> for num in range(3):
alist.append(random.randint(1,6))
>>> print alist
[6, 3, 4]
if you need any more info on list comprehension, just ask.
happy coding
p.s in your code,
loop = True
while loop:
...
you don't need to store True in a variable, just do this:
while True:
...
# OR This
while …
hehe i read about that little scenario when i looked up the rules of risk myself, seems like a complicated little game although i didn't read it that indepth. i'll mess about with mine, see what i can get working or not working.
p.s by the way that bit you do to sort the numbers from highest to lowest. python has a sort function for lists:
>>> alist = [1,2,3,4]
>>> alist.sort(reverse=True) # if you don't have the reverse, you will end up with it lowest to highest.
>>> print alist
[4,3,2,1]
hey no probs i always find it hard understanding other peoples code.
basically, you want to work out who wins right?
well if i'm right, then all you need to do is put that if, else, if, else section of my code into yours, however you will need to change some of the stuff so it works with your code.
to simplify it:
you have a tuple called attack and a tuple called defense right? each contains two numbers, the first being the higher dice roll and the second being the lower dice roll.
To work out the results you need to compare the first number of the attacker against the first number of the defender. If the attackers number is higher than the defenders number then the attacker gains a point. (or in the case of risk, the loser loses a unit) however if not, then the defender gains the point (again in the case of risk; loser loses a unit)
In Code:
if attack[0] > defense[0]:
attackerWins += 1
else:
defenseWins += 1
The second if, else combo does the same thing except it compares the two lower numbers.
In Code:
if attack[1] > defense[1]:
attackWins += 1
else:
defenseWins += 1
then at the end of it all, i simply print the results:
print attackWins
print defenseWins
if your still stuck let me know, glad to help
happy coding
Hello there,
i've been playing around and this seems to have the right result for me:
AttackerWins = 0
DefenderWins = 0
if HighestAttackerRoll > HighestDefenderRoll:
AttackerWins += 1
else:
DefenderWins += 1
if SecondHighestAttackerRoll > SecondHighestDefenderRoll:
AttackerWins += 1
else:
DefenderWins += 1
print "\nOutcome:"
print "Attacker Wins %i" % (AttackerWins)
print "Defender Wins %i" % (DefenderWins)
the result with attack rolls 3, 2 vs defenders rolls 6 and 5:
Outcome:
Attacker Wins 0
Defender Wins 2
i've made some other changes if you want to me to show you feel free to ask, and i'll explain, but thats an answer to the problem :)
happy coding
Looks like a nice program. On my computer (OS = Windows XP) the last tkMessageBox.showinfo() prevents any focus on entry1, no cursor! Strange indeed!
very nice indeed, but i have the same issue, (running windows xp) except it does it to me straight away.
Ok,
I got my hands on win32api, and i've had a little play with your code, and it turns out what i said:
In your case you need to have 'error' after the except followed by the details within the error, which is the section in brackets: except: error (259, 'PyRegEnumValue', 'No more data is available.')
was completely wrong, but here is a solution i've come up with:
import win32api, win32con, sys
aReg = win32api.RegConnectRegistry(None, win32con.HKEY_CURRENT_USER)
aKey = win32api.RegOpenKeyEx(aReg, r"Software\Microsoft\Internet Explorer\PageSetup")
for i in range(100):
try:
Name, Data, Type = win32api.RegEnumValue(aKey, i)
print "Index=(", i,") Name=[", Name,"] Data=[",Data,"] Type=[",Type,"]"
except win32api.error, details: # This part catches win32api's custom error: 'error', then sticks the info that follows into the tuple variable 'details'
if details[0] == 259: # this checks the error type given by win32api the rest is pretty straight forward
print "Error: %s, %s"%(details[1:])
else:
print "Other error"
break
win32api.RegCloseKey(aKey)
The output:
Index=( 0 ) Name=[ header ] Data=[ &w&bPage &p of &P ] Type=[ 1 ]
Index=( 1 ) Name=[ footer ] Data=[ &u&b&d ] Type=[ 1 ]
Index=( 2 ) Name=[ margin_bottom ] Data=[ 0.75000 ] Type=[ 1 ]
Index=( 3 ) Name=[ margin_left ] Data=[ 0.75000 ] Type=[ 1 ]
Index=( 4 ) Name=[ margin_right ] Data=[ 0.75000 ] Type=[ 1 ]
Index=( 5 ) Name=[ margin_top ] Data=[ 0.75000 ] Type=[ 1 ]
Error: PyRegEnumValue, No more data is available.
win32api appears to use it's own error class, …
Here is an example error:
>>> List = ['item1','item2','item3']
>>> for item in range(10):
print List[item]
item1
item2
item3
Traceback (most recent call last):
File "<pyshell#7>", line 2, in -toplevel-
print List[item]
IndexError: list index out of range
>>>
if you look at the traceback bit it tells you some useful information, including the error type which in this case is: IndexError
Now all you have to do is include the error type with the except function:
>>> List = ['item1','item2','item3']
>>> for item in range(10):
try:
print List[item]
except IndexError:
print "There are no more items in the list."
item1
item2
item3
There are no more items in the list (IndexError).
There are no more items in the list (IndexError).
There are no more items in the list (IndexError).
There are no more items in the list (IndexError).
There are no more items in the list (IndexError).
There are no more items in the list (IndexError).
There are no more items in the list (IndexError).
as you can see, the new part of the except command, catches the IndexError and does something about it other than killing the program.
you can have more than one except command too, for example if you wanted to catch a few different types of errors:
>>> for item in range(10):
try:
print List[item]
print List[item]+1
except TypeError:
print "This is a type error"
except IndexError:
print "This is an index error"
except:
print "This is to catch any …
no problem. glad to help :)
Here's my version, slightly adapted, there's probably some new stuff in there if your new to making gui's but just ask about what you might not recognise and i'll explain, it's all pretty simple really
import random
from Tkinter import *
from time import time
def sleep(delay):
stopTime = time()+delay
while time() < stopTime:
mainWindow.update()
return
def clear():
answerLabel.configure(text="")
answerLabel2.configure(text="")
mainWindow.update()
def dieSimulator():
denied = True
startButton.configure(text="Restart")
while denied:
sleep(2)
number = random.randint(1,6)
clear()
if number == 1:
#print "UNO"
strGame = "UNO"
answerLabel.configure(text=strGame)
elif number == 2:
#print "SMASH TV"
strGame = "SMASH TV"
answerLabel.configure(text=strGame)
elif number == 3:
#print "HALO"
strGame = "HALO"
answerLabel.configure(text=strGame)
elif number == 4:
#print "PDZ"
strGame = "PDZ"
answerLabel.configure(text=strGame)
elif number == 5:
#print "COD"
strGame = "COD"
answerLabel.configure(text=strGame)
elif number == 6:
#print "GRAW"
strGame = "GRAW"
answerLabel.configure(text=strGame)
mainWindow.update()
number2 = random.randint(1,2)
restart = dieSimulator
sleep(2)
if number2 == 1:
strGame2 = "Approved"
answerLabel2.configure(text=strGame2)
denied = False
elif number2 == 2:
strGame2 = "Denied"
answerLabel2.configure(text=strGame2)
denied = True
mainWindow.update()
startButton.configure(text = "start")
mainWindow = Tk()
startButton = Button(mainWindow, text="Start", command=dieSimulator, width=20)
startButton.grid(row=0, column=0)
answerLabel = Label(mainWindow, text="Game...", width=20)
answerLabel.grid(row=0, column=1)
answerLabel2 = Label(mainWindow, text="Approved/Denied...", width=20)
answerLabel2.grid(row=1, column=1)
mainWindow.mainloop()
not sure what you mean with the other request, but i think i can help you, i've done loads of work with simple gui's and stuff, just say what you need doing exactly, i'm a bit simple when it comes to understanding stuff
the half a second delay can be done either using:
import time
time.sleep(0.5)
that would be the simplest however the whole code including the GUI would hang as if it crashed, so a slightly more complicated method is doing a while loop, checking the time on each pass, and if it is more than half a second, exiting the loop, and continuing, which is done with the following code:
from time import time
def Delay(delay):
stopTime = time()+delay
while time() < stopTime:
pass
return
Just whack the above function into your code then whenever you want a time delay, just put Delay(0.5) into your code, and it should work
happy coding,
a1eio
when i was first playing about with python (wait... i still am) anyway, a good website is: http://www.bembry.org/
just click on the python section, it has a great simple pdf tut and some quick notes aswell
hmm, what do you mean by include? you can import into your programs using:
import 'module name'
i think the following code may solve your problem, it was thought up by a friend of mine, i merely did the typing, so i take no credit, but i think this is your solution:
def main():
string = "abcd"
k = len(string)
a = 0
SubStrings = []
while k > 0:
SubStrings.append(string[0:a]+string[a+1:])
k -= 1
a += 1
return SubStrings
your putting ':' after the def WordCount() line arn't you, simple i know, but just checking...