Reputation: 77
I seem to have great difficulties understanding how functions pass information to one another. Been teaching myself Python for a while now and I always hit a brick wall.
In the example below the create_list() function knows nothing about playerlist or the tkinter widget playerOption. I really don't know how to overcome this problem!
All help very much appreciated. It's been about 6 hours of work today and I've got nowhere! Thanks in advance.
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()
Upvotes: 3
Views: 3147
Reputation: 143187
playlist
is local variable created in main
. You have to create global
variable to use it in another function.
# 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)
You can skip global playlist
in function if you don't want assign new list to playlist
in that function.
Upvotes: 1