[英]How do I open a file with tkinter and save the data to another variable?
我正在學習使用 tkinter,但我無法弄清楚如何打開文本文件並保存數據,以便可以在其他計算中使用這些數據。 在我下面的代碼中,創建了一個按鈕,按下該按鈕會要求並打開一個文件。 然后它在控制台中打印文件的內容。 如果文件包含例如一個數字,比如 100,我不知道如何將該數字保存為變量,如“a”。
from tkinter.filedialog import askopenfile
root = Tk()
root.geometry('200x100')
# This function will be used to open
# file in read mode and only Python files
# will be opened
def open_file():
file = askopenfile(parent=root, filetypes =[('Text Files', '*.txt')])
if file is not None:
content = file.read()
print(content)
a = content
btn = Button(root, text ='Open', command = lambda:open_file())
btn.pack(side = TOP, pady = 10)
您將文件的內容分配給在 function 中聲明的變量。 它將在 function 完成后銷毀。
在 function 之前聲明變量
data = []
Append 文件內容到function內的容器值
def open_file(container):
file = askopenfile(parent=root, filetypes =[('Text Files', '*.txt')])
if file is not None:
content = file.read()
print(content)
# give the content to the data
data.append(content)
但是,如果您要使用 tk.StringVar() 實例將數據提供給另一個小部件,則可能會更好,因為大多數小部件都有textvariable選項。
data = StringVar()
而不是附加 StringVar 使用 set() 方法。
data.set(content)
為您提供的資源: https://www.pythontutorial.net/tkinter/tkinterstringvar/和: https://www.delftstack.com/howto/python-tkinter/how-to-change-the-tkinter-button-text/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.