【问题标题】:python 2.7 Tkinter how to pass an array in another functionpython 2.7 Tkinter如何在另一个函数中传递一个数组
【发布时间】:2017-11-06 09:48:38
【问题描述】:

使用按钮 (envoi) 打开一个新窗口并在数组中写入元素的值(选择)。在我关闭这个窗口并调用一个函数(window2)之后。 我想阅读此功能中的选择 如果我写 printchoices.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()

【问题讨论】:

  • choices 列表是state 函数的本地列表,所以window2 看不到它。您可以将choices 设为全局,这样两个函数都可以访问它,并且如果它们不重新分配choices 名称,它们将不需要使用global 指令。但是最好把你的GUI放到一个类中,把choices作为一个属性,这样在类的任何地方都可以很容易地访问它。

标签: python python-2.7 tkinter toplevel


【解决方案1】:

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

有几个解决方案:

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

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

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

【讨论】:

    猜你喜欢
    • 2015-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-25
    • 2016-09-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多