global question (python)
I have the code:
from Tkinter import *
admin = Tk()
a = 1
def up():
global a
a += 1
def upp():
up()
print a
print 'its ',a
buttton = Button(admin, text='up', command=upp)
buttton.pack()
mainloop()
I w开发者_运维问答ant to have the "its ",a go up each time i press the button. so kind of replay the code so that, its # would go up by one each time...help
I tested this:
from Tkinter import *
import itertools
admin = Tk()
a = itertools.count(1).next
def upp():
print a()
buttton = Button(admin, text='up', command=upp)
buttton.pack()
mainloop()
This will start a at a value of 1 and each time its printed it will add one more. So the first time you press it, it will display 1 in standard out.
Replace
def upp():
up()
print a
print 'its ',a
buttton = Button(admin, text='up', command=upp)
buttton.pack()
mainloop()
with
def upp():
up()
print 'its ', a
buttton = Button(admin, text='up', command=upp)
buttton.pack()
mainloop()
and it works as you want.
Update: Note that you dont need two functions. A simplified version:
from Tkinter import *
admin = Tk()
a = 0
def upp():
global a
a += 1
print 'its ', a
buttton = Button(admin, text='up', command=upp)
buttton.pack()
mainloop()
anyway global variables should be avoided (see Alan answer for a better solution)
精彩评论