問題描述
獲取python函數的變量 (Get a variable of python function)
我是從python開始的,所以如果我使用的詞彙不合適,請見諒。我創建了一個函數,我想在一個變量中恢復文件所在的位置(它在計算機中的 URL)。
有人能告訴我這怎麼可能嗎?
提前謝謝
from tkinter import*
from tkinter import filedialog
from tkinter.messagebox import*
import tkinter.filedialog
Tk().withdraw()
def insert_photo():
photo = tkinter.filedialog.askopenfilename(title="Ouvrir une image",filetypes=[('Jpg files','.jpg'),('Gif files','.gif'),('Bmp files','.bmp'),('Png files','.png'),('Tiff files','.tif'),('All files','.*')])
return photo
其實我只是想在圖像文件的路徑中獲取一個變量,以便我可以在另一個腳本中更容易地調用它。
我有試過 print(os.path.realpath(__file__))
但問題是,即使 tkinter 窗口長矛。我只是希望該函數在 shell 中執行,並且只有當我調用它時,探索窗口才會打開,並且我可以在變量中獲取路徑。
參考解法
方法 1:
I am not sure exactly what your problem is. I have run your code and it works. Are you after a UNC path?
Have you tried:
>>> p = insert_photo():
>>> print(p)
You seem to have your path already.
If you are trying to open the file dialog in a specific folder you can change the current working directory with os.chdir(PATH)
.
If you only want the folder the image is in you can do os.path.split(PATH)[0]