Để tạo nút Browse mở hộp thoại chọn file, dùng module filedialog. Hàm askopenfile() trả về đối tượng file, có thể đọc nội dung.
Ví dụ minh họa
from tkinter import *
from tkinter import ttk, filedialog
from tkinter.filedialog import askopenfile
win = Tk()
win.geometry("700x350")
def open_file():
file = filedialog.askopenfile(mode='r', filetypes=[('Python Files', '*.py')])
if file:
content = file.read()
file.close()
print("%d ký tự trong file này" % len(content))
Label(win, text="Nhấn nút để duyệt file", font=('Georgia 13')).pack(pady=10)
ttk.Button(win, text="Duyệt", command=open_file).pack(pady=20)
win.mainloop()
Kết quả đầu ra
Cửa sổ có nút Duyệt, chọn file .py sẽ in số ký tự ra console.
