如何在Python 3中通过点击按钮打开文件

0 投票
3 回答
5402 浏览
提问于 2025-04-18 17:45

我想通过点击菜单栏上的一个按钮来打开一个文件(HTML网页文档)。我使用的是Python 3.4和64位的Windows 7。我该怎么做呢?

这个HTML文档保存在我的电脑上,我想从我的电脑上打开它。

3 个回答

0

好的,你可以给菜单栏上的那个按钮设置一个事件处理器,也就是当你点击这个按钮时,会调用一个函数,像这样……

from tkinter import filedialog as fd, messagebox as mb
from webbrowser import open as openlink

def openHTML(file = None):
    if file is None: # browse file in filedialog
        file = fd.askopenfilename(filetypes=(("All Files", "*.*"), ("HTML Documents", "*.html;*.htm"))
    if not file: # if the user didn't cancel
        return
    try: # trying to access the file, if it isn't encrypted or something ..
        open(file, 'r')
    except EnvironmentError as e:
        mb.showerror(title = 'Something isn\'t good ..', detail = e.message)
        return
    openlink(file) # finally, opening the document
0

我不知道在Tkinter中按钮的事件处理器是怎么工作的,但用Python打开一个html链接或文件的命令是:

import webbrowser
webbrowser.open(file_path)

这个命令会在默认的浏览器中打开链接或文件。这里有一个文档链接

1

在Python中创建按钮,可以使用Tkinter这个工具。

import Tkinter
import tkMessageBox

top = Tkinter.Tk()
def helloCallBack():
tkMessageBox.showinfo( "Hello Python", "Hello World")
B = Tkinter.Button(top, text ="Hello", command = helloCallBack)
B.pack()
top.mainloop()

撰写回答