繁体   English   中英

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

[英]How to open a file by clicking a button in Python 3

我想通过单击菜单栏上的按钮来打开文件(HTML Web文档)。 我正在使用Python 3.4和Windows 7 64位。 我将如何去做呢?

HTML文档已保存在我的计算机上,我希望从计算机上将其打开。

要在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()

我不知道按钮的事件处理程序如何在Tkinter中工作,但是打开html链接或文件的python命令是:

import webbrowser
webbrowser.open(file_path)

这将在默认浏览器中打开链接或文件。 这是文档

好吧,您可以在菜单栏上的按钮上设置一个事件处理程序,以调用类似..的函数。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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