全局问题(python)

2024-10-06 11:28:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我有密码:

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

我想有一个“its”,每次我按下按钮,它就会上升。所以重放代码,这样,它的#每次都会上升一个…救命


Tags: textfromimport密码admintkinterdefbutton
2条回答

替换

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

无论如何,应该避免使用全局变量(参见Alan answer以获得更好的解决方案)

我测试了这个:

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英寸标准输出。你知道吗

相关问题 更多 >