【发布时间】:2018-05-27 00:46:44
【问题描述】:
我正在使用一个函数,它允许用户从列表中选择一个项目并将索引存储到一个变量中。我想在函数之外使用该变量,但它不起作用。
这是我目前所拥有的。 (仅供参考:mylist 部分代码未显示)
class FirstWindow(Frame):
selection_index = '0'
def __init__(self, parent, controller):
Frame.__init__(self, parent)
num_lines_lights = 4
scrollbar = Scrollbar(self)
#scrollbar.pack(side=RIGHT, fill=Y)
scrollbar.place(x=55,y=200)
#scrollbar.place(x=25, y=50)
mylist = Listbox(self, yscrollcommand = scrollbar.set)
for line in range(num_lines_lights):
mylist.insert(END, "Light " + str(line))
mylist.pack(side = LEFT, fill = BOTH)
mylist.place(x=70,y=200)
scrollbar.config(command = mylist.yview)
def select_item(event):
global selection_index
widget = event.widget
selection_index = (widget.curselection()[0])
value = widget.get(index)
print("Inside function %s " % selection_index) #works fine
mylist.bind('<<ListboxSelect>>', select_item)
print("This is return %s " % selection_index) #NOT WORKING
这是我收到的错误:
print("This is return %s " % selection_index)
NameError: name 'selection_index' is not defined
【问题讨论】:
-
你为什么将
print声明放入类定义中? -
如果您的代码是我们可以运行和修改的minimal reproducible example,会更容易为您提供帮助。
-
请edit您的问题修复缩进并提供其余代码
-
请您创建一个minimal reproducible example。 “在函数外使用变量”不需要任何 tkinter 库,例如
标签: python python-3.x tkinter