a1eio 16 Junior Poster

Hi,

I'm a bit stuck on getting 1 function that's not inside any class or function, accessible or callable to everyother part of the program, from within classes and the Main function.. i've tried to make it global but i'm not sure on how to make it work and it looks ugly..

Has anyone ever needed to do this before? if so how can it be done, much help needed please

thanks
a1eio

a1eio 16 Junior Poster

lol pygame is fun, give it a go.. hardly industry standard top notch gaming, but you can make some very interesting games :)

a1eio 16 Junior Poster

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.

a1eio 16 Junior Poster

Hi,

there's a few methods, someone asked a similiar question a while back on this forum:
http://www.daniweb.com/forums/thread47882.html

This is a snippet showing how to do it with wxPython (a GUI library like Tkinter but more advanced)
http://www.daniweb.com/code/snippet435.html

and you could also do it using Tkinter and just display each still image yourself onto a canvas using a loop and a delay:
http://www.daniweb.com/forums/post225611-64.html

a1eio 16 Junior Poster

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

a1eio 16 Junior Poster

ah that looks interesting, i'll have a look.

thanks

p.s that is an incredibly small calculator, great coding tips in it, thanks.

a1eio 16 Junior Poster

aah, found out why.

the lambda function needs to be passed the value for 'i' rather than just taking it from the for loop,
instead of:

lambda: buttonClick(i)

it should be:

lambda btn=i: buttonClick(btn)

a1eio

a1eio 16 Junior Poster

Hi,

I'm trying to create 6 buttons in a for loop using tkinter, each button's command points at the same function, but passes a variable (the loop counter.. in this case i) now for some reason.. when i run it, and click on each button, the function is supposed to print the variable passed to it from the button, so i'd expect:

click button 1 -> prints 1 to screen
click button 2 -> prints 2 to screen
etc..

However i end up with:
click button 1 - > prints 6 to screen
click button 2 - > prints 6 to screen again..
click button 3 - > 6 yet again.
etc.. etc

the code i'm using follows:

def buttonClick(button_number):
    print button_number

if __name__ == '__main__':
    root = Tk()
    for i in range(1,6):
        Button(root, text="%i"%(i), command=lambda:buttonClick(i)).grid(row=i, column=2)
        
    root.mainloop()

It seems to be displaying the last value of 'i'?

thanks in advance
a1eio

a1eio 16 Junior Poster

ah, that'll work

good idea

thanks

a1eio 16 Junior Poster

Hi all,

Just wondering if there is a way to see if a window has been destroyed or not.

eg:

root = Tk()

bla ...
bla ...

if root has been destroyed:
    do something...

thanks in advance
a1eio

a1eio 16 Junior Poster

thanks a bunch, i'll look into it.

a1eio 16 Junior Poster

Hello,

I was wondering whether it was possible to embed something made with pygame, like some sort of animated display or bouncing ball whatever, into a Tkinter made window, with tkinter buttons/frames etc...

Anybody heard of this or know of if it can be done?

Thanks
a1eio

a1eio 16 Junior Poster

Ah HA!
Very well explained jrcagle, thanks a bunch.

a1eio

a1eio 16 Junior Poster

yea, i forgot to mention, i'm trying to do this on a windows machine.

the os.popen idea did occur to me, but then i got stuck again.. :p i don't know the dos command for opening the cd drive.

thanks
a1eio

a1eio 16 Junior Poster

hehe, i agree with you, which is why i made the mistake in the first place and didn't even notice it. But yea, that'd be a nice answer cause i havn't a clue.

thanks,
a1eio

a1eio 16 Junior Poster

Hey,

Just a simple question really, i was looking through the documentation for python and i couldn't find anything that did basic cd drive things, like ejecting it and stuff. The one module i did find 'cd' was only compatible on IRIX systems.

After failing miserably on google i was just wondering if anyone happened to know of a command or module that opens the cd drive, and reads from it, seems simple but meh..

I'm hoping theres something built in that does it.

Thanks,
a1eio

a1eio 16 Junior Poster

I LOVE YOU!!!!!!

hehe, thanks it works now.

a1eio

a1eio 16 Junior Poster

Hi,

I'm trying to pin an image to a button, using the 'image' option.
I've looked about on the net and it seems the best way to do it is to create the image in a PhotoImage object. I've done this and then stuck it onto the button but for some reason when it's running, the button assumes the dimensions of the image but it's not displayed, and the button freezes, doesn't respond.

self.Button = Button(self, image=PhotoImage(file="image.gif"))

any help greatly appreciated thanks

a1eio

a1eio 16 Junior Poster

hahahahaha, niice.

thankyou very much, hehe i thought it was probable something simple.

a1eio

a1eio 16 Junior Poster

Hi,

I want to create a little Frame class that has two labels built in, the code snippet below is the class.

class DescriptionFrame(Frame):
    def __init__(self, master, title="", text=""):
        Frame.__init__(master)

        self.title = title
        self.text = text

        self.titleLabel = Label(self, text=self.title, font=("Times", 12, "underline"), fg="darkred")
        self.titleLabel.grid(row=0, column=0, sticky=W)

        self.mainLabel = Message(self, text=self.text, font=("Times", 10), fg="darkgreen")
        self.mainLabel.grid(row=1, column=0, columnspan=1, sticky=EW)

The problem is on line 8, when i try to create the label i get this:

Traceback (most recent call last):
File "C:/Python25/Dialouge1.py", line 34, in __init__
self.titleLabel = Label(self, text=self.title, font=("Times", 12, "underline"), fg="darkred")
File "C:\Python25\lib\lib-tk\Tkinter.py", line 2464, in __init__
Widget.__init__(self, master, 'label', cnf, kw)
File "C:\Python25\lib\lib-tk\Tkinter.py", line 1923, in __init__
BaseWidget._setup(self, master, cnf)
File "C:\Python25\lib\lib-tk\Tkinter.py", line 1901, in _setup
self.tk = master.tk
AttributeError: DescriptionFrame instance has no attribute 'tk'

Now, i was under the opinion that including 'Frame' in brackets after naming the class meant all that 'stuff' (tk attribute for example) was there, and my code would work around it. I'm not too certain where to go from here..

thanks
a1eio

a1eio 16 Junior Poster

yea, ditch the printing and append it to a list and it'll be almost instant. :)

a1eio 16 Junior Poster

has that even been done yet? :P

a1eio 16 Junior Poster

I personally always use the root.destroy() method, it seems to work best and I've never had any problems with it.

a1eio 16 Junior Poster

ah that explains it, and that's a nice solution too, very useful, thanks :)

a1eio 16 Junior Poster

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.

a1eio 16 Junior Poster

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

a1eio 16 Junior Poster

well, thats some interesting code you've got there, and quite a few errors indeed, but most seem to be simple.

for starters, you want the section at the top:

print ''' TEXT KWON DO
The ultimate text based martial arts tournament!
Created especially for the many fine folks at
www.daniweb.com's Python forum. '''
print
raw_input("Press Enter to continue: ")
start()

to go right at the bottom after EVERYTHING else, because if it's at the top, python doesn't know what the 'start()' command is, because it hasn't gotten to that section of the code yet.

after that, there are a few simple indentation errors, on lines 140 141, 166 and 167.

the function prompt_a() has the try, except thing in it, to catch errors that might come from the raw_input (a.k.a the user) great and useful as that is, it's also got the annoying effect of ignoring ("except: pass") any error thats in the rest of your program, so for the meantime i recomend removing the try, except and pass lines so that you can successefully debug your program.

Unfortunantly it's late where i am atm so i'm off to get some sleep.
If you get stuck again just post the problem, and peeps will give you a hand.

Enjoy,
a1eio

a1eio 16 Junior Poster

Hi,

As strange and pointless as this sounds does anybody know how to, or where to obtain a program that could "invert" the colors on the monitor, i know you can invert the colors using the magnifier but i'd like the whole screen to just be inverted, again strange as this may seem, but can it be done??

thanks,
a1eio

a1eio 16 Junior Poster

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.

a1eio 16 Junior Poster

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:

>>>
4

Traceback (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

a1eio 16 Junior Poster

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.

a1eio 16 Junior Poster

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 :)

a1eio 16 Junior Poster

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 …
a1eio 16 Junior Poster

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]
a1eio 16 Junior Poster

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

a1eio 16 Junior Poster

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

a1eio 16 Junior Poster

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.

a1eio 16 Junior Poster

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, …

a1eio 16 Junior Poster

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 …
a1eio 16 Junior Poster

no problem. glad to help :)

a1eio 16 Junior Poster

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()
a1eio 16 Junior Poster

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

a1eio 16 Junior Poster

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

a1eio 16 Junior Poster

The info is on http://www.google.com/apis/

The actual python implementation of it is on: http://pygoogle.sourceforge.net/

It's really simple to use, and pretty neat.

a1eio 16 Junior Poster

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

a1eio 16 Junior Poster

hmm, what do you mean by include? you can import into your programs using:

import 'module name'
a1eio 16 Junior Poster

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
a1eio 16 Junior Poster

I'm trying to use the google/python api, but i keep getting this error thrown at me:

HTTPError: HTTP Error 407: Proxy Authentication Required ( The ISA Server requires authorization to fulfill the request. Access to the Web Proxy service is denied.

I also get this error when trying to use urllib2 to connect to websites. I'm really not very sure how to 'authenticate' i have the required information, it's just i don't know where to use it. like i said i don't really understand it much myself, but any help would be great, thanks.

a1eio 16 Junior Poster

i'm not sure i understand, whats wrong, your code? or is there something else you want to do after??

a1eio 16 Junior Poster

i'm guessing that it would go in the order of which was opened first, bit like a stack maybe, i dunno. but yea it's interesting, i havn't actually found a window which is always on top yet, but when i do i'll let you know