如何使用 Tkinter 创建导入文件按钮?

问题描述:

例如,当您使用记事本(在 Windows 上)并且想要打开旧文件时,您知道如何操作吗?您单击文件,然后打开,然后会打开一个文件对话框,您可以选择所需的文件,程序将显示其内容.

So you know how when you use Notepad (on Windows), for example, and you want to open an old file? You click file, then open, then a file dialog opens ups and you can select the file you want, and the program will display its contents.

基本上,我想用 Python 制作一个按钮,可以做到这一点.

Basically, I want to make a button in Python that can do that exact thing.

这是我的按钮功能-

def UploadAction():
    #What to do when the Upload button is pressed
    from tkinter import filedialog

当我点击分配给这个动作的按钮时,没有任何反应,没有错误,没有崩溃,什么也没有.

When I click on the button assigned to this action, nothing happens, no errors, no crash, just nothing.

import tkinter as tk
from tkinter import filedialog

def UploadAction(event=None):
    filename = filedialog.askopenfilename()
    print('Selected:', filename)

root = tk.Tk()
button = tk.Button(root, text='Open', command=UploadAction)
button.pack()

root.mainloop()