我創建了一個 Tkinter 應用程式,它從另一個檔案呼叫TopLevel物件(用于選單欄選項)。
在我的main.py,我有這個代碼:
...
def create():
funct.createNew()
...
menubar = tk.Menu(window)
#file menu
file = tk.Menu(menubar, tearoff=0)
file.add_command(label='Create new', command=create)
...
并且從functions.py檔案中呼叫的函式(為簡單起見,我洗掉了視窗屬性):
def linkToDB():
global create
#call the function to create virtual file
file = sql.generateDB()
#destroy the createNew window
create.destroy()
#debugging purposes
print("Virtual file:", file)
def createNew():
#make this global to destroy this window later
global create
create = tk.Toplevel()
...
#option 1
container1 = tk.Frame(create)
...
#generate virtual SQLite file
btn1 = tk.Button(container1, text="Create", command= lambda: linkToDB())
上面的代碼顯示了一個TopLevel視窗,該視窗將由Create按鈕 inmain.py呼叫,該視窗又從sql.py(通過TopLevel視窗中的該按鈕)呼叫一個函式來創建臨時 SQlite 檔案:
import sqlite3 as sq
#create a virtual sqlite file
def generateDB():
temp = sq.connect(':memory:')
temp.execute...
return temp
我的問題是如何回傳tempfrom generateDB()to的值main.py(特別是在銷毀TopLevel視窗之后)?我對如何在 .py 檔案中傳遞這個值感到困惑。以及我的方法是否可行(也在尋找建議)。
PS我故意破壞了TopLevel視窗,linkToDB()因為它保證會生成我的臨時SQlite檔案。
uj5u.com熱心網友回復:
您可以修改funct.createNew()以將虛擬檔案回傳到main.py. 但是,您需要將頂層視窗設定為模態視窗,以便在頂層視窗被銷毀后回傳虛擬檔案。
以下是修改后的functions.py:
import tkinter as tk
import sql
# pass the toplevel window as an argument instead of using global variable
def linkToDB(create):
# use an attribute of the toplevel window to store the "virtual db file"
create.file = sql.generateDB()
create.destroy()
print('Virtual file:', create.file)
def createNew():
create = tk.Toplevel()
...
container1 = tk.Frame(create)
...
btn1 = tk.Button(container1, text='Create', command=lambda: linkToDB(create))
...
# wait for window destroy (works like a modal dialog)
create.wait_window(create)
# return the "virtual db file"
return create.file
然后你可以得到虛擬資料庫檔案main.py:
def create():
# if you want the "virtual db file" be accessed by other function
# declare it as global variable
#global db_file
db_file = funct.createNew()
print(db_file)
...
...
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/486926.html
上一篇:功能亂序執行?
下一篇:lambda事件:做什么?
