Trying tkinter for first time. The code below has 4 print# statements. Two questions here -
1)- When executing, I expected the of flow of code would be same as print# statements but seems the flow is different . I see print2,3 first and then print1. why is it so ?
2)- Only print1 and 4 have value of variable u_input ( or e1.get ) . Why are print2,3 dont show the same value ? .. its probably same reason as flow of code.
from tkinter import *
w = Tk()
w.title(" Main Window")
w.geometry('800x800')
def test ():
ux = u_input.get()
print("print1 : " , ux )
u_input = StringVar()
e1 = Entry(w , textvariable = u_input )
e1.grid(row=0,column=1, padx = 300 , pady= 20 )
b1 = Button(w, text ="button1", width = 12 , justify = "center", command = test )
b1.grid(row=10,column=1 , padx= 300 , pady= 40)
print("print 2 : ", str(u_input.get()))
print("print 3 : ", str(e1.get()))
w.mainloop()
User_Entry = str(u_input.get())
print("print 4 ", User_Entry)
===============================
comparing above code to one below - this one prints in the order the functions are called.
a= 1
b= 2
def func2 ():
a=100
b=200
print("print3 :", a+b)
def func1 ():
a=10
b=20
print("print1 :",a+b)
func1()
print("print2 :", a+b)
func2()
All GUIs work different then command
input().Button()doesn't wait for your click - it only creates information formainloop()what widget it has to display in window - and latermainloop()starts program and it displays window and all widgets in this window. And it runs loop which gets keyboard/mouse events from system, sends them to widgets, runs function when you click some button, (re)draw widgets, etc.So
"print 2","print 3"is executed beforemainloop()shows window - and before you can click button which runs code with"print 1".And the same is with second problem. In
"print 2","print 3"it prints values beforemainloop()displays window and before you can put any text inEntry.As I said the same way works other GUIs - not only
tkinterbutPyQt,PyGTK, etc. And not only inPythonbut also in other languagesC,C++,Java, etc.The same way may work also games - they also may have some
event loop. InPyGameyou have to even write this loop on your own.