I created a Tkinter app that calls TopLevel
objects from another file (for menu bar options).
In my main.py
, I have this code:
...
def create():
funct.createNew()
...
menubar = tk.Menu(window)
#file menu
file = tk.Menu(menubar, tearoff=0)
file.add_command(label='Create new', command=create)
...
And the function being called from functions.py
file (I removed the window attributes for simplicity):
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())
The above code displays a TopLevel
window that will be called by Create button in main.py
, which in turn calls a function from sql.py
(by that button within TopLevel
window) to create temporary SQlite file:
import sqlite3 as sq
#create a virtual sqlite file
def generateDB():
temp = sq.connect(':memory:')
temp.execute...
return temp
My problem is how to return the value of temp
from generateDB()
to main.py
(specifically after destroying the TopLevel
window)? I am confused on how to pass this value across the .py files. And whether my approach is viable or not (also looking for suggestions).
P.S. I intentionally destroyed the TopLevel
window in linkToDB()
since it is guaranteed that my temporary SQlite file will be generated.
CodePudding user response:
You can modify funct.createNew()
to return the virtual file to main.py
. However you need to make the toplevel window a modal window in order to return the virtual file after the toplevel window is destroyed.
Below is the modified 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
Then you can get the virtual db file in 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)
...
...