I am trying to build a GUI using Tkinter. As it will get crowded I try to split it into multiple scripts. How can I pass return values from one button function/command to another button which executes a whole different script but uses the return value of button1 for one of its functions?
So what I want is this. It is juts a rough sketch but I think one can understand what I am aiming for. I am open to different approaches.
GUI.py
import functions
arg1 = 1
button1 = tk.Button(...., command = lambda: functions.addOne(arg1))
button2 = tk.Button(**Run program executeTHIS.py with return value from button1 command**)
functions.py
addOne(arg1):
value = arg1 1
return value
executeThis.py
functionNeedingArgumentFromButton1(value):
...
return something
...
...
CodePudding user response:
I think best would be to use wrapper functions for your Buttons. This seems not efficient for this case, but when you have complex operations this will keep your GUI.py
readable. Here I use a global variable
to share the value between Buttons and functions.
GUI.py
import tkinter as tk
from my_functions import addOne
from my_functions2 import functionNeedingArgumentFromButton1
value = 1
def wrapper1():
global value
value = addOne(value)
var.set(value)
def wrapper2():
global value
value = functionNeedingArgumentFromButton1(value)
var.set(value)
if __name__ == '__main__':
root = tk.Tk()
root.title("Import functions")
Button1 = tk.Button(root, text="Run1", command=wrapper1)
Button1.pack()
Button2 = tk.Button(root, text="Run2", command=wrapper2)
Button2.pack()
var = tk.StringVar()
var.set('0')
label1 = tk.Label(root, textvariable=var)
label1.pack()
root.mainloop()
my_functions.py
def addOne(arg1):
value = arg1 1
return value
my_functions2.py
def functionNeedingArgumentFromButton1(value):
value = value 100
return value
CodePudding user response:
One simple way is to change arg1
to IntVar()
:
import functions
from executeThis import functionNeedingArgumentFromButton1
...
arg1 = tk.IntVar(value=1)
button1 = tk.Button(..., command=lambda: functions.addOne(arg1))
button2 = tk.Button(..., command=lambda: functionNeedingArgumentFromButton1(arg1.get()))
...
functions.py
...
def addOne(arg):
arg.set(arg.get() 1)
...
executeThis.py
...
def functionNeedingArgumentFromButton1(value):
# do whatever you want on 'value'
...
...