[英]How to return value from a widget`s function, and pass it to another widget's function in Tkinter, Python
[英]python 2.7 Tkinter how to pass an array in another function
使用一個按鈕(envoi),我打開一個新窗口,並在數組中(選擇)寫入元素的值。 在我關閉此窗口並調用函數(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上面所述, choices
是state()
局部變量,這意味着window2()
不知道任何稱為choices
list
。
有幾種解決方案:
首先,可能也是最不推薦的choices
,您可以choices
一個可以從任何地方訪問的全局變量。 這可能會導致命名沖突,並且可能更令人沮喪,以后再回來更改此代碼。
其次,當聲明調用window2()
的Button
小部件時,您可以添加choices
作為要傳遞給函數的參數。
第三,最個人建議,您可以重寫GUI以包含一個class
, class
使您可以在該類本地使用任何函數均可訪問的變量。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.