【问题标题】:How to open a file by clicking a button in Python 3如何通过单击 Python 3 中的按钮打开文件
【发布时间】:2014-08-19 05:44:01
【问题描述】:

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

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

【问题讨论】:

  • 您可以使用webbrowser 模块在浏览器中打开页面。如何将它连接到菜单栏取决于您使用的 GUI 框架...
  • 我正在使用 Tkinter,但我只想让它在任何浏览器中打开 .html 文件,默认设置在用户的计算机上 - 可能是 Google Chrome、Mozilla Firefox 或 Internet Explorer .

标签: python html python-3.x tkinter menubar


【解决方案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()

【讨论】:

    【解决方案2】:

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

    import webbrowser
    webbrowser.open(file_path)
    

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

    【讨论】:

      【解决方案3】:

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

      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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-02-07
        • 2017-07-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-09-01
        • 2014-11-06
        • 1970-01-01
        相关资源
        最近更新 更多