簡體   English   中英

將值從 TopLevel 對象返回到根對象的 Tkinter 方法

[英]Tkinter method on returning value from TopLevel object to root object

我創建了一個 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窗口,該窗口將由main.py中的Create按鈕調用,然后調用sql.py中的一個函數(通過TopLevel窗口中的那個按鈕)來創建臨時 SQlite 文件:

import sqlite3 as sq

#create a virtual sqlite file
def generateDB():
    temp = sq.connect(':memory:')
    temp.execute...
    return temp

我的問題是如何將temp的值從generateDB()返回到main.py (特別是在破壞TopLevel窗口之后)? 我對如何在 .py 文件中傳遞這個值感到困惑。 以及我的方法是否可行(也在尋找建議)。

PS 我故意破壞了linkToDB()中的TopLevel窗口,因為它保證會生成我的臨時 SQlite 文件。

您可以修改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)
    ...

...

暫無
暫無

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

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