V
V
va11662021-08-13 12:28:43
Python
va1166, 2021-08-13 12:28:43

How to output intermediate results of a calculation to a tkinter element?

What needs to be changed in the code so that an intermediate result is displayed in the tkinter element (in this particular case, the canvas) (what the print("x=",x) function displays in the code below. Thanks for the answers, I can’t think of anything on my own ( (

from tkinter import *
from random import *

def calc(event):
    x = 0 
    while x != 5:
        x = randrange (1,10,1)
        print("x=",x)
        canv.delete("canvtext")
        canv.create_text(50, 50, font=("Verdana", 20), text=str(x), anchor=CENTER, tags=('canvtext')) 

root = Tk()
root.geometry('640x480+400+90')
but = Button(root, text='Рассчитать', width=10, height=3, font=("arial", 12))

canv = Canvas(root, bg="lightgray", height=100, width=100, highlightthickness=0)
canv.create_text(50, 50, font=("arial", 20), text=str(0), anchor=CENTER, tags=('canvtext')) 

but.pack()
canv.pack()
but.bind("<Button-1>", calc)
 
root.mainloop()

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vindicar, 2021-08-13
@Vindicar

In most cases, when you change a control, it doesn't redraw itself immediately - it only takes note that it will need to redraw itself at the first opportunity. And the first opportunity it will have is when your calc() handler is done.
Therefore, there are a couple of options.
1. call inside the loop in calc() root.update_idletasks(). This will pause your handler and give the controls a chance to render, and then resume execution.
2. Break the handler into separate short (this is important!) iterations. At the end of each iteration, schedule the next iteration with root.after() if required. Then, in the intervals between the completion of the current iteration and the call of the planned next iteration, the tkinter will have time to draw.
In both cases, you should foresee / check what will happen if you press the button twice. I suspect no good, so the button should be disabled for the duration of the handler.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question