tkinter匯入檔案

2021-09-05 11:22:53 字數 1881 閱讀 9602

自學tkinter,針對「檔案匯入」所走過的坑:

通過在網上查詢,很容易找到filedialog為tkinter的檔案匯入模組,即from tkinter import filedialog,filedialog內建功能原始檔寫的很簡潔就不多說了,這裡要提的就是askdirectory,它只能記錄到檔案所在的資料夾。在此主要介紹askopenfilenames。

import tkinter as tk

from tkinter import filedialog

from main_program import road_images

window = tk.tk()

def open_file():

filename = filedialog.askopenfilename(title='開啟txt檔案', filetypes=[('txt', '*.txt')])

return filename

button_import = tk.button(window, text="匯入檔案",command=open_file)

button_impprt.pack()

這樣可以直接開啟檔案,非常方便,但我需要獲取檔案路徑,於是加了一句

filename = open_file()
這樣寫就會引發乙個很蛋疼的問題,就是剛執行程式時就會自動開啟選擇檔案對話方塊,網上查半天依然找不到解決的辦法,後面才想到借用entry功能,完整**如下:

import tkinter as tk

from tkinter import filedialog

window = tk.tk()

window.geometry("500x300")

def open_file():

filename = filedialog.askopenfilename(title='開啟txt檔案', filetypes=[('txt', '*.txt')])

entry_filename.insert('insert', filename)

# 設定button按鈕接受功能

button_import = tk.button(window, text="匯入檔案", command=open_file).pack()

# 設定entry

entry_filename = tk.entry(window, width=30, font=("宋體", 10, 'bold'))

entry_filename.pack()

# 嘗試輸出

def print_file():

a = entry_filename.get() #用get提取entry中的內容

print(a)

tk.button(window, text="輸出", command=print_file).pack()

window.mainloop()

問題解決

注意1、由於在函式中呼叫了entry_filename.insert,因此entry_filename不能像button那樣直接在後面接

pack()啟用。

2、將檔名賦值出去時,盡量在函式內部進行,若檔名用的地方不多,建議全程直接採用函式,不必賦值出去,即:

# 嘗試輸出

def print_file():

print(entry_filename.get())

tk.button(window, text="輸出", command=print_file).pack()

window.mainloop()

因為將檔名賦值出去後,容易出現值為空的情況,具體原因我也不清楚。

python檔案匯入 python 檔案匯入

基本匯入 import time 呼叫的時候 time.sleep 3 匯入包裡某個方法 from time import sleep 呼叫的時候 sleep 3 區別import time和from time import sleep 兩種方法都可以成功匯入,但不同的匯入方式,呼叫的方式也不同。如...

python GUI程式設計 Tkinter

python 提供了多個圖形開發介面的庫,幾個常用 python gui 庫如下 tkinter 是 python 的標準 gui 庫。python 使用 tkinter 可以快速的建立 gui 應用程式。由於 tkinter 是內建到 python 的安裝包中 只要安裝好 python 之後就能 ...

匯入dmp檔案

建立命名空間 命名空間名字 create tablespace bbsp logging size 50m autoextend on next 50m maxsize 512m extent management local 建立使用者jnbbsp 密碼jnbbsp 命名空間 bbsp creat...