sw123456
sw123456

Reputation: 3459

Understanding the logic of Tkinter mainloop() and why variables are not reassigned their original values?

From my understanding window.mainloop() keeps repeating the GUI code so that the window and its widgets stay on the screen. Why, therefore, can a variable (such as canvastext) be updated and stay updated? Surely the logic of window.mainloop() would overwrite canvastext so that it once again has the text value 'Hi' instead of the new spinbox value? It may be that I have completely misunderstood what window.mainloop() does but if it does make the program keep looping through the code then why aren't variables reassigned their original values?

from tkinter import *

x = 10
y = 10
a = 100
b = 100

def hello():
    #print spin value
    print ("Spin Value:")
    number = v.get()
    print(number)
    #update text with variable value
    txt = v.get()
    global canvastext
    canvas1.delete(canvastext)
    canvas1.update()
    canvastext = canvas1.create_text(50, 50, text = txt)

window = Tk()
window.geometry("500x500")

#canvas and drawing
canvas1=Canvas(window, height = 200, width = 400)
canvas1.grid(row=0, column=0, sticky=W)
coord = [x, y, a, b]
rect = canvas1.create_rectangle(*coord, outline="#fb0", fill="#fb0")
canvastext = canvas1.create_text(50, 50, text ="Hi")

# create a toplevel menu
menubar = Menu(window)

firstmenu = Menu(menubar, tearoff=0)
firstmenu.add_command(label="Hello!", command=hello)
firstmenu.add_command(label="Quit!", command=window.destroy)
menubar.add_cascade(label="Menu1", menu=firstmenu)

secondmenu = Menu(menubar, tearoff=0)
secondmenu.add_command(label="Hi!", command=hello)
secondmenu.add_command(label="Quit!", command=window.destroy)
menubar.add_cascade(label="Menu2", menu=secondmenu)

window.config(menu=menubar)

#spinboxes and capturing value
v=IntVar()
spin = Spinbox(window, textvariable=v, from_=1, to = 10)
spin.grid(row=1, column = 0, sticky= W)

window.mainloop()

Upvotes: 0

Views: 987

Answers (1)

Bryan Oakley
Bryan Oakley

Reputation: 385910

"From my understanding window.mainloop() keeps repeating the GUI code so that the window and its widgets stay on the screen"

Not exactly. It doesn't "keep repeating" anything, except to keep looking for events and dispatching the handlers for the events. It doesn't re-run any of your code. mainloop is very simple, it's not much different than this:

while (the_main_window_hasnt_been_destroyed):
    event=event_queue.pop()
    event.handle()

I don't understand your question about variables getting reset. The event loop by itself does not alter anything. All it does is wait for events and then call the appropriate handler. If a handler changes a variable, it gets changed. If not, it stays the same.

Upvotes: 4

Related Questions