"export" 从函数到全局变量的元组
"export" a tuple from function to a global variable
我编写了一个函数,使用 Tkinter 提取列表框中的选定选项。打印命令只有在我直接在函数中编写时才有效。如何在函数外打印元组?
这是失败代码:
Traceback (most recent call last):
File "C:/Users/....", line 68, in <module>
print (selection)
NameError: name 'selection' is not defined
我试图将元组转换为全局变量。
def doStuff():
global selected
selected = lb.curselection()
if selected: # only perform if user made a selection
for index in selected:
selection = (lb.get(index))# how you get the value of the selection from a listbox
print(selection)
```
在函数内部设置的变量只能从函数内部访问。您需要将 return selection
添加到函数的末尾,然后执行 print(doStuff())
您可以像下面这样在函数范围之外访问 selection
。但请记住在函数范围外打印 selection
变量之前调用 doStuff()
函数。
selected = None
selection = None
def doStuff():
global selected, selection
selected = lb.curselection()
if selected: # only perform if user made a selection
for index in selected:
selection = (lb.get(index))# how you get the value of the selection from a listbox
print(selection)
我编写了一个函数,使用 Tkinter 提取列表框中的选定选项。打印命令只有在我直接在函数中编写时才有效。如何在函数外打印元组?
这是失败代码:
Traceback (most recent call last):
File "C:/Users/....", line 68, in <module>
print (selection)
NameError: name 'selection' is not defined
我试图将元组转换为全局变量。
def doStuff():
global selected
selected = lb.curselection()
if selected: # only perform if user made a selection
for index in selected:
selection = (lb.get(index))# how you get the value of the selection from a listbox
print(selection)
```
在函数内部设置的变量只能从函数内部访问。您需要将 return selection
添加到函数的末尾,然后执行 print(doStuff())
您可以像下面这样在函数范围之外访问 selection
。但请记住在函数范围外打印 selection
变量之前调用 doStuff()
函数。
selected = None
selection = None
def doStuff():
global selected, selection
selected = lb.curselection()
if selected: # only perform if user made a selection
for index in selected:
selection = (lb.get(index))# how you get the value of the selection from a listbox
print(selection)