简体   繁体   English

如何使用 tkinter 打开文件并将数据保存到另一个变量?

[英]How do I open a file with tkinter and save the data to another variable?

I am learning to use tkinter and I cannot figure out how to open a text file and save the data so that I can use the data in other calculations.我正在学习使用 tkinter,但我无法弄清楚如何打开文本文件并保存数据,以便可以在其他计算中使用这些数据。 In my code below a button is created that when pressed asks for and opens a file.在我下面的代码中,创建了一个按钮,按下该按钮会要求并打开一个文件。 It then prints the content of the file in the console.然后它在控制台中打印文件的内容。 If the file contains for example a single number, say 100, I can't figure out how to save that number as a variable like "a."如果文件包含例如一个数字,比如 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)

You are assigning the contents of the file to a variable declared within the function.您将文件的内容分配给在 function 中声明的变量。 It will be destroyed after the function finishes.它将在 function 完成后销毁。

Declare the variable before the function在 function 之前声明变量

data = []

Append the content of the file to the container value within the function 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)

However if you are going to give the data to another widget using a instance of tk.StringVar() might be better as most widgets have a textvariable option.但是,如果您要使用 tk.StringVar() 实例将数据提供给另一个小部件,则可能会更好,因为大多数小部件都有textvariable选项。

data = StringVar()

And instead of appending StringVar uses the set() method.而不是附加 StringVar 使用 set() 方法。

data.set(content)

Resources for you: https://www.pythontutorial.net/tkinter/tkinterstringvar/ And: https://www.delftstack.com/howto/python-tkinter/how-to-change-the-tkinter-button-text/为您提供的资源: 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM