I want to open a file (HTML web document) by clicking a button on my menu bar. I am using Python 3.4 and Windows 7 64-bit. How would I go about doing this?
The HTML document is saved on my computer, I want it open it from my computer.
For creating button in Python use Tkinter widget.
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:
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.