Home > OS >  Tkinter program does not terminate
Tkinter program does not terminate

Time:12-02

import threading
import tkinter
from tkinter import *

flag = False

def terminate_prog():
    global win3, mylabel
    global flag
    flag = True
    win3.destroy()


def loop_func():
    global flag, mylabel
    while True:
        if flag:
            break
        else:
            mylabel.config(text="Loop")



global mylabel
global button_win3_end
global win3
win3 = tkinter.Tk()
win3.geometry("700x500")

mylabel = Label(win3, text="Text")
mylabel.pack()

check_thread = threading.Thread(target=loop_func)
check_thread.start()

button_win3_end = Button(win3, text="Exit", command=lambda: terminate_prog)
button_win3_end.place(x=40, y=400)

win3.mainloop()

In the code, there is a label in the window and 'loop_func' function called by check_thread that is used to continuously run the loop. When I click on exit, the loop terminates because flag is True, but window is not destroyed and the program does not terminate. terminate_prog function should terminate the program but it does not.

CodePudding user response:

I have left comments in the code, for the purpose of self learning.

Also see:

import tkinter as tk
#import tkinter once and avoid wildcard imports
import types

namespace = types.SimpleNamespace()
#use simplenamespace instead of all these global statements
namespace.flag = False
namespace.num = 0

def terminate_prog():
    #win3/mylabel is already in the global namespace
    namespace.flag = True
    win3.destroy()


def loop_func():
    if namespace.flag:
        return #do nothing
    else:
        mylabel.config(text=namespace.num)
        namespace.num  = 1
        win3.after(100, loop_func)

#it is useless to global in the global namespace
win3 = tk.Tk()
win3.geometry("700x500")

mylabel = tk.Label(win3, text="Text")
mylabel.pack()
button_win3_end = tk.Button(win3, text="Exit", command=terminate_prog)
#lambda is not needed, so don't use it
button_win3_end.place(x=40, y=400)

#use an after loop instead of threading
loop_func()

win3.mainloop()
  • Related