将tkinter变量传递给另一个函数

时间:2015-11-27 15:06:03

标签: python tkinter

我似乎很难理解函数如何将信息传递给彼此。一直在教我自己的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()

1 个答案:

答案 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功能。