使用 Tkinter 读取文件内容可以使用 Python 的内置文件读取功能。以下是一个示例程序,演示如何使用 Tkinter 打开文件对话框,选择文件并读取其内容:

import tkinter as tk
from tkinter import filedialog

root = tk.Tk()
root.withdraw()

file_path = filedialog.askopenfilename()
if file_path:
    with open(file_path, 'r') as file:
        file_content = file.read()
        print(file_content)

这个程序首先创建了一个 Tkinter 窗口,但是通过调用 root.withdraw() 方法隐藏了它。然后使用 filedialog.askopenfilename() 方法打开了一个文件对话框,允许用户选择要读取的文件。如果用户选择了文件,程序将打开该文件,读取其内容并打印出来。注意,此处使用了 with 语句来自动关闭文件。

Tkinter 读取文件内容:使用文件对话框选择并读取文件

原文地址: https://www.cveoy.top/t/topic/nUsm 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录