我有一個簡單的 GUI,用戶可以在其中選擇一個檔案,該檔案成為我的主代碼的變數。在這里,我的變數輸出應該是gui_db_path用戶輸入的資料庫路徑()。當我運行這個名為 的代碼時gui_test.py,該變數是可列印的,并列印到控制臺。
class GUI:
def __init__(self, window):
# 'StringVar()' is used to get the instance of input field
self.input_db_text = StringVar()
window.title("HyPep 1.0")
window.geometry("700x700")
ttk.Label(window, text='Database sequences .csv:').grid(row=1,column=0)
ttk.Button(window, text = "Browse", command = lambda: self.set_path_database_field()).grid(row = 1,column=2, ipadx=5, ipady=0)
ttk.Entry(window, textvariable = self.input_db_text, width = 70).grid( row = 1, column = 1, ipadx=1, ipady=1)
ttk.Button(window, text = "Analyze").grid(row = 10,column=1, ipadx=5, ipady=15)
def set_path_database_field(self):
self.path_db = askopenfilename()
self.input_db_text.set(self.path_db)
def get_database_path(self):
""" Function provides the database full file path."""
return self.path_db
if __name__ == '__main__':
window = tkinter.Tk()
gui = GUI(window)
window.mainloop()
print(gui.path_db, '\n', gui.path_qu)
gui_db_path = gui.path_db
print(gui_db_path)
我的問題是我需要檢索此變數以在另一個檔案中使用user_input.py,但不再可呼叫。我的代碼user_input.py是:
from gui_test import gui_db_path
print(gui_db_path)
在這種情況下,我沒有列印到控制臺,而是得到:
ImportError: cannot import name 'gui_db_path' from 'gui_test'
我確定我缺少一個簡單的解決方案,任何人都可以闡明一下嗎?
...更新:更接近,需要擴展解決方案:
我將如何擴展它以檢索多個路徑?我一直在嘗試這個:
gui_test.py:
...
def get_db_path():
window = tkinter.Tk()
gui = GUI(window)
window.mainloop()
return gui.get_database_path()
def get_qu_path():
window = tkinter.Tk()
gui = GUI(window)
window.mainloop()
return gui.get_query_path()
user_input.py:
from gui_test import get_db_path
from gui_test import get_qu_path
gui_db_path = get_db_path()
gui_qu_path = get_qu_path()
uj5u.com熱心網友回復:
請注意,if __name__ == '__main__'檔案匯入時不會執行塊內的代碼。您需要將這些代碼放在函式中,并在函式末尾回傳路徑:
gui_test.py
...
def get_db_path():
window = tkinter.Tk()
gui = GUI(window)
window.mainloop()
return gui.get_database_path()
然后在里面匯入這個函式user_input.py:
from gui_test import get_db_path
gui_db_path = get_db_path()
print(gui_db_path)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/407103.html
標籤:
