我無法弄清楚如何從 filedialog.askopenfilename 存盤值。現在我將值保存到區域變數,但我想稍后在其他函式中使用這個值。我無法回傳這個值,因為我在創建按鈕時呼叫了函式。但是我想避免使用全域變數。我怎樣才能做到這一點?還有其他方法嗎?這是代碼:
from tkinter import Tk, StringVar, ttk
from tkinter import filedialog
from tkinter import messagebox
def browse_files():
filename = filedialog.askopenfilename(initialdir = "/",
title = "Select a File",
filetypes = (("Text files",
"*.txt*"),
("all files",
"*.*")))
print(filename)
root = Tk()
button1 = ttk.Button(root,text='Browse', command=browse_files)
button1.grid(row=0,column=0)
uj5u.com熱心網友回復:
下面是一個使用類和實體變數的例子:
from tkinter import Tk, ttk
from tkinter import filedialog
class App(Tk):
def __init__(self):
super().__init__()
self.filename = None
button1 = ttk.Button(self, text='Browse', command=self.browse_files)
button1.grid(row=0, column=0)
button2 = ttk.Button(self, text='Show', command=self.show)
button2.grid(row=0, column=1)
def browse_files(self):
# use instance variable self.filename
self.filename = filedialog.askopenfilename(initialdir="/",
title="Select a File",
filetypes=(("Text files", "*.txt*"),
("all files", "*.*")))
def show(self):
print(self.filename)
root = App()
root.mainloop()
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/365149.html
上一篇:如何使檔案夾路徑通用?
