[英]Pass tkinter variable to another function
我似乎很難理解函數如何相互傳遞信息。 我自學 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
列表。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.