Skip to main content
 首页 » 编程设计

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

2025年05月04日16mayingbao

我似乎很难理解函数如何相互传递信息。自学 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() 

请您参考如下方法:

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) 

如果您不想在该函数中将新列表分配给 playlist,则可以跳过函数中的 global playlist。