บางครั้งในขณะที่สร้างแอปพลิเคชัน เราจำเป็นต้องโต้ตอบกับโปรแกรมและแอปพลิเคชันภายนอก ในการโต้ตอบกับแอปพลิเคชันและโปรแกรมของระบบ เราต้องใช้ os โมดูลในหลาม
ในบทความนี้ เราจะมาดูกันว่าเราสามารถโต้ตอบกับโปรแกรมภายนอกและ openfiles โดยใช้โมดูล 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() ผลลัพธ์
การเรียกใช้โค้ดข้างต้นจะสร้างหน้าต่างต่อไปนี้เป็นผลลัพธ์ -

ตอนนี้ คลิกปุ่มและจะเปิดโฟลเดอร์ “My Documents” จากตำแหน่งที่คุณสามารถเปิดโปรแกรมได้