简体   繁体   中英

error when exiting tkinter window update and update_idletasks

I have a problem with functions update() and update_idletasks() in tkinter they work fine except that when closing the window, either by cliking the "Exit" button or the "x" to close the window in Windows, the following error lines show up:

Traceback (most recent call last): File "D:\Python\VisualStudio\test4\test4\test4.py", line 14, in label.configure(text = str(i)) # i is actually updated by an asynchronous function, like a wifi stream File "C:\Users\Owner\AppData\Local\Programs\Python\Python310\lib\tkinter_ init _.py", line 1675, in configure return self. configure('configure', cnf, kw) File "C:\Users\Owner\AppData\Local\Programs\Python\Python310\lib\tkinter_ init .py", line 1665, in _configure self.tk.call(_flatten((self._w, cmd)) + elf._options(cnf)) _tkinter.TclError: invalid command name "..label" Press any key to continue. . .

Ultimately I want Tkinter to show the incoming characters from a wi-fi, which is why I cannot use mainloop.

I want to display the characters coming asynchronously from a wifi on a Tkinter window After several problems I was able to come to the following solution. Many thanks to JRiggles and Bryan Oakles

This is my source code:

import tkinter as tk

def my_async(): # this simulates my asynchronous function, i will come from wifi
    global i
    i = i+1

i = 0
window_is_alive = True

root = tk.Tk()
label = tk.Label(root,text="Name")
label.pack()

def destroy_window():
    global window_is_alive
    window_is_alive = False

#Reassign the Close Window Control Icon
root.protocol("WM_DELETE_WINDOW", destroy_window)

exit_button = tk.Button(root, text="Exit", command=destroy_window)
exit_button.pack()

while True:
    label.configure(text = str(i)) # i is actually updated by an asynchronous function, like a wifi stream
    my_async()                     # these two lines are just to simulate that
    root.update_idletasks()
    root.update()
    if window_is_alive == False:
        root.destroy()
        break
    

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM