簡體   English   中英

使用 Tkinter 獲取其他 function 使用的文件路徑

[英]Getting file path for use by other function using Tkinter

我剛開始使用 Tkinter,所以請不要在這方面評判我……我想獲取 csv 文件的路徑,然后在不終止程序的情況下使用它。 以下代碼有效,但是,我退出程序:

from tkinter import *
from tkinter import filedialog


root = Tk()
root.title('ask and print path to file')


def get_path():
    global path
    path = filedialog.askopenfile(title = 'Select the .csv file with keywords', filetypes = (('csv files','*.csv'), ('All files', '*.*')))

path_button = Button(root, text = 'Select keywords', command = get_path)
path_button.pack()


button_quit = Button(root, text ='Exit', command = root.quit)
button_quit.pack(side = BOTTOM)


root.mainloop()

print(path.name)

這里的打印語句只是為了簡單起見(實際上我想使用pd.read_csv(path.name)來讀取文件,進行一些爭論然后返回更改的文件)。

如何在不退出后台 GUI 的情況下進行print(path.name)

我會將按鈕命令更改為執行所有文件代碼的 function:

# update the button to call a different function
path_button = Button(root, text = 'Select keywords', command = handle_file)

# make a new function to handle everything
def handle_file():
    path = get_path()
    pd.read_csv(path.name)
    # any other stuff

# change this function too, so that it returns a value to "handle_file* rather than setting a global variable
def get_path():
   return filedialog.askopenfile(title = 'Select the .csv file with keywords', filetypes = (('csv files','*.csv'), ('All files', '*.*')))

這樣您就不用使用全局變量,並且您的代碼可以在您獲取文件后執行某些操作。 其本質是在獲取路徑的同時執行處理代碼( pd.read_csv() )。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM