2015-11-27 67 views
2

我似乎很難理解函數如何將信息傳遞給另一個函數。一直教我自己的Python一段時間,我總是撞到一堵磚牆。將tkinter變量傳遞給另一個函數

在下面的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

playlistmain創建的本地變量。您必須創建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

+0

謝謝!我被告知要儘可能避免全局變量,儘管如此我試圖不這樣做。 – INoble

+0

@INoble:「避免全局變量」的建議太廣泛了。導入和定義創建全局名稱。建議應該是「不要使用全局變量來避免將對象傳遞給函數和從函數返回對象」。在編寫gui回調函數時,框架確定簽名,您必須使用全局變量或類來在函數之間傳遞值。 –

+0

@TerryJanReedy我認爲這是一些很好的建議。我一直在試圖擺脫所有的全局變量,這似乎沒有道理。我想自學的危險! – INoble

相關問題