简体   繁体   English

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

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

I want to open a file (HTML web document) by clicking a button on my menu bar. 我想通过单击菜单栏上的按钮来打开文件(HTML Web文档)。 I am using Python 3.4 and Windows 7 64-bit. 我正在使用Python 3.4和Windows 7 64位。 How would I go about doing this? 我将如何去做呢?

The HTML document is saved on my computer, I want it open it from my computer. HTML文档已保存在我的计算机上,我希望从计算机上将其打开。

For creating button in Python use Tkinter widget. 要在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()

I do not know how event handlers for a button work in Tkinter, but the python command to open an html link or file is: 我不知道按钮的事件处理程序如何在Tkinter中工作,但是打开html链接或文件的python命令是:

import webbrowser
webbrowser.open(file_path)

This opens the link or file in the default browser. 这将在默认浏览器中打开链接或文件。 Here's the documentation . 这是文档

Well, You can set an event handler attached to that button on your menu bar calling a function like this .. 好吧,您可以在菜单栏上的按钮上设置一个事件处理程序,以调用类似..的函数。

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