I currently have a main python script (main.py) which reads input from a second script (input.py) which can be modified by a user. The user sets variables such as number of dimensions (ndim), number of points (npts) etc. in the second script and these are read into main.py using the following:
filename = sys.argv[-1]
m = __import__(filename)
ndim = m.ndim
npts1 = m.npts1
npts2_recorded = m.npts2_recorded
The script is executed by the following command:
python main.py input
I would like to replace input.py with a GUI. Tkinter seems a sensible place to start and I can see how to create a GUI to enable the user to set the various options that they would otherwise have set in input.py. However, I do not know how to pass this information to main.py from the GUI. Is there an equivalent to __import(filename)__ which can extract information from selections made by a user in the GUI, or is there another way of achieving the same effect.
A minimal (not) working example based on the answer below:
This code creates the file example.txt but the text given to block1 does not get written to the file.
from Tkinter import *
def saveCallback():
with open("example.txt",'w') as outfile:
outfile.write(block1.get())
def UserInput(status,name):
optionFrame = Frame(root)
optionLabel = Label(optionFrame)
optionLabel["text"] = name
optionLabel.pack(side=LEFT)
var = StringVar(root)
var.set(status)
w = Entry(optionFrame, textvariable= var)
w.pack(side = LEFT)
optionFrame.pack()
return w
if __name__ == '__main__':
root = Tk()
block1 = UserInput("", "Block size, dimension 1")
Save_input_button = Button(root, text = 'Save input options', command = saveCallback())
Save_input_button.pack()
root.mainloop()
Use a file for that, save selections in the GUI to a file(just like you did before with input.py) and then read the file.
So, in your main.py
The only drawback here is that you have to make sure in your main.py script that the GUI have been already closed. For that you can use the subprocess module, there are several function there you can use for block until the process returns or ends.
With this approach you just have to type:
python main.py
and somewhere inside main.py:
# The function call will wait for command to complete, then return the returncode attribute.
rcode = subprocess.call(['python', 'gui_input.py'])
import tkinter
top = tkinter.Tk()
def saveCallback():
with open("example.txt", 'w') as outfile:
outfile.write(e1.get())
e1 = tkinter.Entry(top)
b1 = tkinter.Button(top, text ="Save", command = saveCallback)
e1.pack(side=tkinter.LEFT)
b1.pack(side=tkinter.RIGHT)
top.mainloop()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With