python - Tkinter program does not behave as I think it should -


my counter not stop. when hit start 2nd time want continue counting , not restart.

from tkinter import *  master = tk()  counter_activation_variable=3  def start():     counts=0     counter_activation_variable=0     button.configure(text = "stop", command=stop)       while counter_activation_variable == 0:         counts = counts+1         textbox.delete(1.0, end)         textbox.insert(end,(counts))     master.update()  def stop():     counter_activation_variable=5     button.configure(text = "start", command=start)     master.update()  button = button(master, text="start",command=start, bg="grey") button.pack(side='bottom', fill='none', expand=false, padx=4, pady=4) master.title("stopwatch")  textbox = text(master, height=1, width=175) textbox.pack(side='top', fill='none', expand=false, padx=4, pady=4)  master.mainloop() 

you have 2 problems here. bigger, more obvious 1 scoping problem.

the short answer need 2 lines fix this.

def start():  global counter_activation_variable  # add  counts=0 ... def stop():  global counter_activation_variable  # ,  counter_activation_variable = 5 

if don't this, variable counter_activation_variable inside start() method refer different variable happens have name counter_activation_variable inside of stop() method, totally separate third variable in global scope named counter_activation_variable.

this because python allows reference variables in specific areas, called scopes. variable defined in function exists inside function. if want write global variable, have explicitly mark global. (python lets read directly global variable without declaring inside function first)

the second function, alluded earlier, threading problem. i'm thinking while loop in start() occupy of computation time , so, when button clicked again, stop() method may not execute correctly.

however, don't know enough tkinter know if handles kind of gui multi-threading -- could.


Comments