I am using Python 3 with tkinter. When pressing a button, a child window should pop up containing a spinbox. The initial value of the spinbox should be a parameter. The child window also contains a "Set" button. When the button is pressed, the child window should close and the value of the spinbox should be passed to the parent application.
In my minimal non-working example, the spinbox in the main window and its corresponding button work as expected. However, the same code in the child window does not work, neither the initial value is set correctly nor the value of the spinbox is returned to the main application.
import tkinter as tk
class spin_child:
def __init__(self, value, callback):
self.root = tk.Tk()
self.callback = callback
self.var_spin = tk.IntVar()
self.spin = tk.Spinbox(self.root, from_=0, to=100, textvariable=self.var_spin, width=10)
self.spin.pack()
self.button = tk.Button(self.root, text="Set", command=lambda: self.return_value(self.var_spin.get()), width=20)
self.button.pack()
def close_window(self):
self.root.destroy()
def return_value(self, value):
self.callback(value)
self.root.destroy()
def run(self):
self.root.mainloop()
def callback(value):
print(value)
root = tk.Tk()
btn = tk.Button(root, text="Open Window", command=lambda: spin_child(20, callback), width=50)
btn.pack()
var_spin = tk.IntVar()
var_spin.set(20)
spin = tk.Spinbox(root, from_=0, to=100, textvariable=var_spin, width=10)
spin.pack()
btn = tk.Button(root, text="Local Spin", command=lambda: print(var_spin.get()), width=50)
btn.pack()
root.mainloop()
I also tried implementing my child window as a function instead of a class with no change in behaviour.
import tkinter as tk
def spin_child(value, callback):
def return_value(value):
callback(value)
root.destroy()
root = tk.Tk()
callback = callback
var_spin = tk.IntVar()
spin = tk.Spinbox(root, from_=0, to=100, textvariable=var_spin, width=10)
spin.pack()
button = tk.Button(root, text="Set", command=lambda: return_value(var_spin.get()), width=20)
button.pack()
root.mainloop()
def callback(value):
print(value)
root = tk.Tk()
btn = tk.Button(root, text="Open Window", command=lambda: spin_child(20, callback), width=50)
btn.pack()
var_spin = tk.IntVar()
var_spin.set(20)
spin = tk.Spinbox(root, from_=0, to=100, textvariable=var_spin, width=10)
spin.pack()
btn = tk.Button(root, text="Local Spin", command=lambda: print(var_spin.get()), width=50)
btn.pack()
root.mainloop()
I can't really wrap my head around what could be the problem here, any thoughts?
Thanks in advance!
In second script, the callback
function.
Edit:
Use one tk()
and one mainloop()
will do entirely script, while Toplevel()
will do one, but no need to add mainloop()
.
On line 8, this may cause problem. So use Toplevel()
On line 8, change this root = tk.Toplevel()
instead of tk.Tk()
On line 17, comment out #root.mainloop()
On line 22, add var_spin.set(value)
Snippet:
def callback(value):
print(value)
var_spin.set(value)