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

Cách chọn thư mục và lưu vị trí dùng Tkinter Python

Quen với hộp thoại trong nhiều ứng dụng. Dialog hữu ích khi tương tác người dùng là yếu tố chính. Dùng dialog chọn file, thực hiện đọc/ghi file. Dialog tạo bằng Module filedialog Python.

Ví dụ

Tạo ứng dụng yêu cầu chọn file, hiển thị vị trí bằng Label.

#Import Tkinter library
from tkinter import *
from tkinter import ttk
from tkinter import filedialog
#Tạo instance Tkinter frame
win= Tk()
#Đặt geometry
win.geometry("750x250")
def select_file():
    path= filedialog.askopenfilename(title="Select a File", filetype=(('text files''*.txt'),('all files','*.*')))
    Label(win, text=path, font=13).pack()
#Tạo Label và Button mở dialog
Label(win, text="Click the Button to Select a File", font=('Aerial 18 bold')).pack(pady=20)
button= ttk.Button(win, text="Select", command= select_file)
button.pack(ipadx=5, pady=15)
win.mainloop()

Kết quả

Chạy mã hiển thị cửa sổ có nút chọn file, hiển thị đường dẫn.

Cách chọn thư mục và lưu vị trí dùng Tkinter Python

Chọn file bất kỳ, hiển thị vị trí trong Label.

Cách chọn thư mục và lưu vị trí dùng Tkinter Python