Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีเปิดโปรแกรมภายนอก (External Programs) ด้วย Tkinter

บางครั้งขณะสร้างแอปพลิเคชัน เราต้องโต้ตอบกับโปรแกรมและแอปพลิเคชันภายนอก เพื่อโต้ตอบกับแอปพลิเคชันและโปรแกรมของระบบ เราต้องใช้โมดูล os ใน Python

ในบทความนี้ เราจะดูวิธีโต้ตอบกับโปรแกรมภายนอกและเปิดไฟล์โดยใช้โมดูล OS ใน Python

ก่อนอื่น เราจะกำหนดฟังก์ชันที่จะเปิดไฟล์ที่เลือกโดยใช้ไลบรารี filedialog ใน Python จากนั้นพิมพ์ Path และเปิดไฟล์โดยใช้โมดูล 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()

ผลลัพธ์

การรันโค้ดข้างต้นจะผลิตหน้าต่างต่อไปนี้เป็นผลลัพธ์:

วิธีเปิดโปรแกรมภายนอก (External Programs) ด้วย Tkinter

ตอนนี้ คลิกปุ่ม และมันจะเปิดโฟลเดอร์ "My Documents" ซึ่งจากนั้นคุณสามารถเปิดโปรแกรมได้