[英]Python Tkinter get result of askopenfilenames()
我使用 Tkinter 作為 GUI 庫,我需要通過調用 askopenfilenames 來獲取我選擇的文件列表。 這是我的功能^
def choose_file(file_list)
file_list = fd.askopenfilenames()
file_list = ()
b1 = Button(command = lambda: choose_file(file_list))
file_list - 在外部 scope 中是變量。 但是調用function后,這個var是空的。 我做錯了什么?
嘗試:
import tkinter.filedialog as fd
import tkinter as tk
def choose_file():
global file_list
file_list = fd.askopenfilenames()
file_list = ()
root = tk.Tk()
b1 = tk.Button(root, text="Click me", command=choose_file)
b1.pack()
root.mainloop()
變量file_list
不是全局的,因為它是不可變的。 要使其全局化,您必須將global file_list
添加到 function 定義的開頭。 有關更多信息,請閱讀: 如果它是 global ,為什么你可以更改 immutable 。
您的代碼中有兩個不同的file_list
變量。 全球一台 scope
file_list = ()
一個在 function scope。
def choose_file(file_list):
和
file_list = fd.askopenfilenames()
you are assigning the list returned by askopenfilenames
to the function scope variable - everywhere in the function, file_list
will have the list from askopenfilenames
as value, what you can see by adding print(file_list)
to your function twice, one time at the beginning and最后一次。
要修改全局變量而不是局部變量,您可以將局部(函數范圍)變量設為全局變量
file_list = ()
def choose_file():
global file_list
file_list = fd.askopenfilenames()
b1 = Button(command = choose_file)
其中變量初始化必須在 function 聲明之前移動(我認為否則它會給出UnboundLocalError
或其他東西),可以刪除 lambda,並且您不需要將file_list
作為參數傳遞。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.