Home > Back-end >  Import many variables from Tkinter GUI into another script without realaunching GUI
Import many variables from Tkinter GUI into another script without realaunching GUI

Time:06-30

I have a Tkinter GUI with many variables that are obtained from a user's input. I then have a separate script that calls each of these variables for use in downstream calculations. The issue is that when I call a variable from the second script, it relaunches the GUI each time. Is there a way around this, so that the variables are available without relaunching the GUI again?

GUI.py:

root = Tk()
choice1 =  IntVar()
choice2 = IntVar()
choice3 =  StringVar()
root.mainloop()

*I have simplified the GUI script above, but essentially the user inputs their values into a Tkinter Entry box, and the input is assigned to the variable when a "submit" button is clicked.

retrieve.py:

from GUI import choice1
from GUI import choice2
from GUI import choice3

I have also tried rewriting retrieve.py, but the same results were produced:

from GUI import *

CodePudding user response:

If you run retrieve.py as separate script then all your idea is wrong.

Every program runs in separated process with separated memory (for security: (1) so one program can't get passwords to your bank account from other program, (2) when one program crashs then other programs still can work).

When retrieve.py imports other module then it runs all code for the beginning and it creates new variables in own memory and it doesn't give access to variables created when you run GUI.py.

GUI.py should write data in file, and retrieve.py should read data from this file.

More complex method is to use socket, queue or shmem (shared memory) to communicate between processes.


GUI.py

import tkinter as tk  # PEP8: `import *` is not preferred
import json

# --- functions ---

def save():
    data = [choice1.get(), choice2.get(), choice3.get()]
    with open('data.json', 'w') as fh:
        json.dump(data, fh)
        label['text'] = 'saved'
    
# --- main ---

root = tk.Tk()

choice1 = tk.IntVar(root)
choice2 = tk.IntVar(root)
choice3 = tk.StringVar(root)

entry1 = tk.Entry(root, textvariable=choice1)
entry1.pack()

entry2 = tk.Entry(root, textvariable=choice2)
entry2.pack()

entry3 = tk.Entry(root, textvariable=choice3)
entry3.pack()

button = tk.Button(root, text='Save', command=save)
button.pack()

label = tk.Label(root)
label.pack()

root.mainloop()

retrieve.py

import json

# --- functions ---

def load():
    with open('data.json') as fh:
        data = json.load(fh)
        return data
    
# --- main ---

data = load()

if data:

    choice1, choice2, choice3 = data
    
    print('choice1:', choice1)
    print('choice2:', choice2)
    print('choice3:', choice3)

else:

    print('wrong file')
  • Related