如何定义通过另一个函数内的for循环创建的全局变量?

时间:2017-05-26 05:10:58

标签: python python-2.7 for-loop tkinter global-variables

我收到错误

  

NameError:全局名称' spinbox_0'未定义

当我尝试从我的一个Tkinter旋转框中获取值并将其打印出来时。旋转框位于另一个函数中,如果可能的话我会定义它,但是我不知道如何在这个实例中因为旋转框的名称和数量是由for循环创建的,具体取决于主题列表的长度。

我认为发布调试代码会更容易。错误代码显示何时按下Button two按钮。

目前我只想检索spinbox_0值并打印出来。之后我将使用另一个循环来获取所有的spinbox值。

from Tkinter import Tk, Button, Spinbox, Label

## Create a window
window = Tk()

## Give the window a title
window.title('Tester')

names = ['Name 1','Name 2','Name 3','Name 4','Name 5','Name 6','Name 7']

## Define the actions for when button one is pushed
def button1():
    print "Button one pushed"
## Create the Spinboxes for each name in the list
    spinbox_list = []
    spinbox_grid_list = []
    for number, name in enumerate(names):
        spinbox = 'spinbox_' + str(number) + ' = Spinbox(window, width = 3, from_=0, to=10)'
        spinbox_grid = 'spinbox_' + str(number) + '.grid(padx = 0, pady = 0, row = 13, column = '+ str(number) +')'
        spinbox_list.append(spinbox)
        spinbox_grid_list.append(spinbox_grid)
        spinbox_option = {'spinbox_{}'.format(i):e for i, e in enumerate(spinbox_list)}
    spinbox_option_string = '\n'.join(spinbox_option.values())
    spinbox_grid_option = {'spinbox_grid_{}'.format(i):e for i, e in enumerate(spinbox_grid_list)}
    spinbox_grid_option_string = '\n'.join(spinbox_grid_option.values())
    exec(spinbox_option_string)
    exec(spinbox_grid_option_string)
## Create a second button
    button_two = Button(window, text = 'Button two', command = button2, width = 20)
    button_two.grid(pady = 10, padx = 2, row = 14, columnspan = 9, sticky = "S") 

## Define the actions for when button two is pushed (print the spinbox values)
def button2():
    print 'spinbox_0 = ' + (spinbox_0.get())
    ## spinbox_0 is Just an example. I need all spinboxes to print out their
    ## values here somehow

button_one = Button(window, text = 'Button one', command = button1, width = 20)
button_one.grid(pady = 2, padx = 2, row = 1, columnspan = 9, sticky = 'S')

window.mainloop()

1 个答案:

答案 0 :(得分:1)

认识到全局变量是一个坏主意的事实,这是一种方法。制作全局变量,然后不要在函数内重新分配它。您现在可以在button2函数中循环显示它。由于您需要Spinbox对象而不是其描述,请将保存为

*顺便说一句,通过避免exec,您可以严格简化button1功能。

spinboxes = []


# Define the actions for when button one is pushed
def button1():
    print "Button one pushed"
    # Create the Spinboxes for each name in the list
    spinbox_grid_list = []
    for number, name in enumerate(names):
        spinboxes.append(Spinbox(window, width=3, from_=0, to=10))
        spinboxes[number].grid(padx=0, pady=0, row=13, column=number)
    button_two = Button(window, text='Button two', command=button2, width=20)
    button_two.grid(pady=10, padx=2, row=14, columnspan=9, sticky="S")

# Define the actions for when button two is pushed (print the spinbox values)
def button2():
    for i, spinbox in enumerate(spinboxes):
        print 'spinbox_{} = '.format(i) + (spinbox.get())

我认为button1只被调用过一次。否则,每次按下时,这将继续向全局列表添加新的spinbox es。绕过那个:

def button1():
    print "Button one pushed"

    global spinboxes
    spinboxes = []
    ...

我们使用global关键字让我们重新分配全局对象,每次调用函数时都将其清除。