[英]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.