如何使用 Tkinter 打开外部程序?
有时,在创建应用程序时,我们需要与外部程序和应用程序进行交互。为了与系统的应用程序和程序进行交互,我们必须在 Python 中使用os模组。
在本文中,我们将了解如何使用 Python 中的 OS 模组与外部程序进行交互并打开文件。
首先,我们将定义一个函数,它将使用 Python 中的filedialog库打开所选文件。然后,我们将在使用os模组的情况下打印路径并打开文件。
举例
# Import the required Libraries
from tkinter import *
from tkinter import filedialog
import os
#Create an instance of tkinter frame
win= Tk()
#Set the geometry for the window or frame
win.geometry("600x400")
#Define a function to open the application
def app():
file= filedialog.askopenfilename()
text.config(text= file)
#Open the program
os.system('"%s"' %file)
#Create a button
Button(win, text='Click to Open a Program',font=('Poppins bold', 10),
command=app).pack(pady=20)
#Create a Label after button event
text= Label(win, text= "", font= ('Poppins bold', 10))
text.pack(pady=20)
#Keep running the window or frame
win.mainloop()输出
运行以上代码将产生如下所示的窗口作为输出 −

现在,单击此按钮,将打开“我的文档”文件夹,您可以在其中打开程序。
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP