我似乎很难理解函数如何将信息传递给彼此。一直在教我自己的Python一段时间,我总是碰壁砖。
在下面的示例中, create_list()函数对 playerlist 或tkinter小部件 playerOption 一无所知。我真的不知道如何克服这个问题!
非常感谢所有人的帮助。今天已经工作了大约6个小时,我无处可去!提前谢谢。
from tkinter import *
def create_list(surname):
table = r'c:\directory\players.dbf'
with table:
# Create an index of column/s
index = table.create_index(lambda rec: (rec.name))
# Creates a list of matching values
matches = index.search(match=(surname,), partial=True)
# Populate playerOption Menu with playerlist.
playerlist = []
for item in matches:
playerlist.append([item[4], item[2], item[1]])
m = playerOption.children['menu']
m.delete(0, END)
for line in playerlist:
m.add_command(label=line,command=lambda v=var,l=line:v.set(l))
def main():
master = Tk()
master.geometry('{}x{}'.format(400, 125))
master.title('Assign a Player to a Team')
entry = Entry(master, width = 50)
entry.grid(row = 0, column = 0, columnspan = 5)
def get_surname():
surname = entry.get()
create_list(surname)
surname_button = Button(master, text='Go', command=get_surname)
surname_button.grid(row = 0, column = 7, sticky = W)
# Menu for player choosing.
var = StringVar(master)
playerlist = ['']
playerOption = OptionMenu(master, var, *playerlist)
playerOption.grid(row = 1, column = 1, columnspan = 4, sticky = EW)
mainloop()
main()
答案 0 :(得分:1)
playlist
是在main
中创建的局部变量。您必须创建global
变量才能在另一个函数中使用它。
# create global variable
playlist = ['']
#playlist = None
def create_list(surname):
# inform function `create_list` to use global variable `playlist`
global playlist
# assign empty list to global variable - not to create local variable
# because there is `global playlist`
playerlist = []
for item in matches:
# append element to global variable
# (it doesn't need `global playlist`)
playerlist.append([item[4], item[2], item[1]])
def main():
# inform function `main` to use global variable `playlist`
global playlist
# assign list [''] to global variable - not to create local variable
# because there is `global playlist`
playlist = ['']
# use global variable
# (it doesn't need `global playlist`)
playerOption = OptionMenu(master, var, *playerlist)
如果您不想在该功能中为global playlist
分配新列表,则可以跳过playlist
功能。