使用def add()在Tkinter中预先形成x = x + 1:

时间:2013-12-12 06:11:29

标签: tkinter

每次尝试此程序时都会出错。

from Tkinter import *
def returnCodeno():
    print 'no'
    choice = choice + 1
    textEnter('no')
root = Tk()
choice = 0
Yes = Button(root,text = 'Yes',width = 15, command = returnCodeno)
Yes.pack()
root.mainloop()

我每次尝试点击是

时都会收到此错误消息
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1470, in __call__
return self.func(*args)
File "C:\Users\Stephen Tafoya\Desktop\Stanley parable text based\stanley2.py", line 6, in returnCodeno
choice = choice + 1
UnboundLocalError: local variable 'choice' referenced before assignment

任何帮助都会有很大帮助。

1 个答案:

答案 0 :(得分:1)

我想您想要访问choice中的模块级变量returnCodeno而不是创建新的本地变量,因此您必须使用global语句。

示例:

from Tkinter import *
def returnCodeno():
    global choice
    choice += 1
    print choice

root = Tk()
choice = 0
Yes = Button(root,text = 'Yes',width = 15, command = returnCodeno)
Yes.pack()
root.mainloop()