python 2.7 Tkinter 如何在另一个函数中传递数组

python 2.7 Tkinter how to pass an array in another function

使用按钮 (envoi) 我打开一个新的 window 并在数组中写入元素的值(选择)。在我关闭此 window 并调用函数 (window2) 之后。 我想阅读此功能中的选择 如果我写 print choices.get(),我有一个错误:未定义全局名称 'choices'

# -*- coding: utf-8 -*-
from Tkinter import *

root = Tk()
group = LabelFrame(root, text=" 1. Paramètrage: ")

group.grid(row=0, columnspan=5, sticky='W', \
          padx=5, pady=5, ipadx=5, ipady=5)

dropVar2=StringVar()
dropVar2.set("----")
opt3 = OptionMenu(group, dropVar2, '----', 'Pondéraux', 'Atomiques')
opt3.grid(row=4, column=1, columnspan=7, sticky='WE', padx=5, pady=2)

def state():
    if dropVar2.get()=='Atomiques':
        winE=Toplevel(root)
        group = LabelFrame(winE, text="Pourcentages atomiques", padx=5,pady=5)
        group.pack(padx=25, pady=25)

        entries = []
        j = 0
        choices = ['C', 'Ni', 'Co', 'Fe', 'Cr', 'Al', 'Ti', 'Ta', 'Nb',
               'Hf', 'V', 'Re', 'Mo', 'W', 'B', 'Zr', 'Mg', 'Y']
        while j < len(choices) :
            valeurOneLabel = Label(group, text=choices[j])
            valeurOneLabel.grid(row=j+1, column=0, columnspan=1, sticky='WE', padx=5, pady=2)
            en = Entry(group, text="")
            en.grid(row=j+1, column=1)
            entries.append(en)
            j+=1
        for s in range(len(choices)):
            choices[s] = entries[s]

        exitButton = Button(winE, text = 'Close', command = lambda:  window2(winE)).pack()


def window2(winE):
    winA=Toplevel(root)
    winA.geometry('400x600+600+50')
    print choices.get()
    winE.destroy()

Button(group, text='envoi', command = state).grid(row=5, column=0)




root.geometry("450x350+100+100")
root.title("Développement d'alliages")
root.mainloop()

正如 PM 2Ring 上面所述 choicesstate() 的局部变量,这意味着 window2() 不知道任何 list 调用choices.

有几种解决方法:

首先,可能也是最不推荐的,您可以使 choices 成为一个可以从任何地方访问的全局变量。这可能会导致命名冲突,并使稍后返回并更改此代码变得更加令人沮丧。

其次,当您声明调用 window2()Button 小部件时,您可以添加 choices 作为要传递给函数的参数。

第三点也是我个人最推荐的,你可以重写你的 GUI 以包含一个 class 这将允许你拥有可以被任何函数访问的 class 的本地变量。