Suspend execution until user input is received from tkinter window
I'm trying to do something that looks like something that should be simple at first glance.
I am performing a series of operations in Python to complete them before the following:
operation1() operation2() operation3()
However, it operation2()
requires user input from a tkinter input box in a popup. As soon as I create this popup is executed operation3()
. How can I prevent this? operation2()
can create a popup and introduce an undefined loop, but the button in the popup should trigger a function that breaks that loop. What's the best way to do this? It is important to operation2()
finish before starting operation3()
.
Apologies if I'm not clear, but I completely confused myself trying to make this work.
source to share
One way to do this is to make the main window ( root
) so that the popup launches it.
This is achieved by creating a popup as usual (using a widget Toplevel()
that I would assume) and then calling root.wait_window(theToplevel)
.
I created a small example of how this is done, I think it should give you this idea.
Essentially, he is asking int
. A popup appears on success (name it operation 2
), which will prompt you for something else int
. When finished, the operation 2
command of the OK
main window button changes to operation 3
, which will destroy the window. However, I could just call op3
after the call root.wait_window(new)
; this will destroy the main window after the popup finishes (or whatever it op3
should do).
I've also included a for loop that just prints the range; this means that nothing will continue until Toplevel
data collection is complete.
Here's some sample code:
from Tkinter import *
from tkMessageBox import *
root = Tk()
val = 0
val2 = 0
def op1():
global e, l, root, val, e2, b, new
try:
val = int(e.get())
except ValueError:
showerror("Error", "Enter an int")
else:
new = Toplevel()
e2 = Entry(new)
e2.pack(side = LEFT)
b2 = Button(new, text = "OK", command = op2)
b2.pack(side = RIGHT)
l2 = Label(new, text = "Enter new number to multiply %d by" %val)
l2.pack()
e2.focus_force()
root.wait_window(new)
for i in range(5):
print (i + 1)
def op2():
global val
try:
val2 = int(e2.get())
except ValueError:
showerror("Error", "Enter an int")
e2.focus_force()
else:
val = val * val2
l.config(text = "This is your total: %d Click OK to exit" %val)
new.destroy()
b.config(command = op3)
def op3():
root.destroy()
e = Entry(root)
e.pack(side = LEFT)
b = Button(root, text = "OK", command = op1)
b.pack(side = RIGHT)
l = Label(root, text = "Enter a number")
l.pack()
root.mainloop()
Hope this helps you solve your problem.
source to share