Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Cách mở chương trình bên ngoài (External Programs) bằng Tkinter?

Đôi khi ứng dụng cần tương tác với chương trình hệ thống. Dùng module os của Python.

Dùng filedialog chọn file, in đường dẫn, mở file bằng os.system().

Ví dụ

# Import thư viện
from tkinter import *
from tkinter import filedialog
import os

win = Tk()
win.geometry("600x400")

def app():
    file = filedialog.askopenfilename()
    text.config(text=file)
    # Mở chương trình
    os.system('"%s"' % file)

Button(win, text='Click to Open a Program', font=('Poppins bold', 10), command=app).pack(pady=20)
text = Label(win, text="", font=('Poppins bold', 10))
text.pack(pady=20)

win.mainloop()

Kết quả

Chạy code hiển thị cửa sổ.

Cách mở chương trình bên ngoài (External Programs) bằng Tkinter?

Click nút mở hộp thoại chọn file từ "My Documents".