2011-04-23 90 views
0

我的代码:全球问题(蟒蛇)

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

我想拥有“它”,一个每次我按下按钮上去。这么样的重播代码,这样,其#将上浮了每次一...帮助

回答

4

我测试了这一点:

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

这将在值1开始,每一次它的印刷它将增加一个。所以第一次按下它时,它会在标准输出中显示1。

+0

哎呦。感谢代码引号joaquin。 – Alan 2011-04-23 06:56:18

+0

测试并编辑了我的示例。除非我误解,否则它似乎按照他的要求工作。 – Alan 2011-04-23 07:04:01

+0

+1你对,对不起 – joaquin 2011-04-23 07:09:19

1

更换

def upp(): 
    up() 
    print a 
print 'its ',a 
buttton = Button(admin, text='up', command=upp) 
buttton.pack() 
mainloop() 

def upp(): 
    up() 
    print 'its ', a 
buttton = Button(admin, text='up', command=upp) 
buttton.pack() 
mainloop() 

,当你想它的工作原理。

更新:请注意,你不需要两个功能。一个简化的版本:

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

反正全局变量应避免(见一个更好的解决方案阿兰回答)