日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達(dá)者為師

網(wǎng)站首頁(yè) 編程語(yǔ)言 正文

python使用tkinter模塊實(shí)現(xiàn)文件選擇功能_python

作者:非典型假猿 ? 更新時(shí)間: 2022-08-20 編程語(yǔ)言

前言

學(xué)習(xí)Python中,總想做個(gè)圖形界面,找來找去,找到了tkinter。

練習(xí)內(nèi)容:圖形界面中,點(diǎn)擊按鈕后,利用彈出對(duì)話框選擇文件(或文件夾)

1.導(dǎo)入庫(kù)和模塊

import tkinter as tk
from tkinter import filedialog

此處練習(xí)過程中出現(xiàn)的錯(cuò)誤:在沒有第2個(gè)導(dǎo)入語(yǔ)句時(shí),使用 tk.filedialog 后,提示錯(cuò)誤,顯示

Cannot find reference ‘filedialog’ in 'init.py

我查了“Lib/tkinter/"文件夾,發(fā)現(xiàn)里面并沒有 tkinter.py,但是有 filedialog.py
我想著:tkinter是庫(kù),filedialog是模塊吧,
但為啥 tk.filedialog不能用?
反而,在有第2個(gè)導(dǎo)入語(yǔ)句時(shí),用 tk.filedialog 和 filedialog 都可以

出錯(cuò)情況 :

正常情況:

2.編寫按鈕命令

def select_file():
    # 單個(gè)文件選擇
    selected_file_path = filedialog.askopenfilename()  # 使用askopenfilename函數(shù)選擇單個(gè)文件
    select_path.set(selected_file_path)  
def select_files():
    # 多個(gè)文件選擇
    selected_files_path = filedialog.askopenfilenames()  # askopenfilenames函數(shù)選擇多個(gè)文件
    select_path.set('\n'.join(selected_files_path))  # 多個(gè)文件的路徑用換行符隔開
def select_folder():
    # 文件夾選擇
    selected_folder = filedialog.askdirectory()  # 使用askdirectory函數(shù)選擇文件夾
    select_path.set(selected_folder)

注意:三個(gè)按鈕命令中,變量select_path是主窗體中Entry控件的textvariable屬性值,在窗體初始化過程中,需要為其賦值:

select_path = StringVar()

3. 窗體初始化及布局

root = tk.Tk()
root.title("選擇文件或文件夾,得到路徑")
# 初始化Entry控件的textvariable屬性值
select_path = tk.StringVar()
# 布局控件
tk.Label(root, text="文件路徑:").grid(column=0, row=0, rowspan=3)
tk.Entry(root, textvariable = select_path).grid(column=1, row=0, rowspan=3)
tk.Button(root, text="選擇單個(gè)文件", command=select_file).grid(row=0, column=2)
tk.Button(root, text="選擇多個(gè)文件", command=select_files).grid(row=1, column=2)
tk.Button(root, text="選擇文件夾", command=select_folder).grid(row=2, column=2)
root.mainloop()

4.運(yùn)行

選擇了單個(gè)文件的情況

原文鏈接:https://blog.csdn.net/fan0829/article/details/119984383

欄目分類
最近更新