无效的命令名称“.!label3”

invalid command name ".!label3"

我正在创建一个游戏,当疫苗达到 100 时,游戏结束,用户将转到胜利屏幕。见下文

import random
from tkinter import *

#creates new window
root = Tk()

#makes backdrop picture of map
C = Canvas(root, bg="black", height=780, width=1347)
C.grid(row=0,column=0)


#vaccine label creation and place
vaccineLabel=Label(root, text="10000", font ="algerian 25", bg = "Light Blue")
vaccineLabel.place(x=271 ,y=706, relwidth=1/5, relheight=0.1)


totalDeaths = 0
totalPopulation = 1
vaccineCount = 95

#loops until total deaths = population
def simulate_Count():


    def update_Count():
        
        #calls global variables
        global vaccineCount


        #vaccine determination
        vaccine1 = random.randint(0,0)
        vaccine2 = random.randint(0,0)
        if vaccine1 == vaccine2:
            vaccineCount += 1

        #updates labels
        vaccineLabel.config(text = f'Deaths:{vaccineCount}')

        
        if vaccineCount == 100:
            def victory_Screen():

                #calls global root and deletes
                global root
                root.destroy()                           

                #creates the window
                root = Tk()

                #assembles the dimension of the window, and the colour
                C=Canvas(root, bg="black", height=780, width=1347)
                C.grid(row=0, column=0)
                
                #creates a label which will print the game title and places it in the correct dimensions
                victoryLabel=Label(root, text=f"YOU HAVE WON! \n IT ONLY TOOK YOU", bg="black", fg="light grey")
                victoryLabel.place(x=0, y=0, relwidth=1, relheight=1)
            victory_Screen()
            
                
    update_Count()


    #loops until deaths = population
    if totalDeaths < totalPopulation:
        root.after(1000, simulate_Count)

simulate_Count()

这给我带来了一个错误。当我销毁 window 并创建一个新的时,会显示新的 window。但是,由于某种原因,这些行中发生错误,错误类型为 invalid command name ".!label3"

包含错误的行如下:

#updates labels
vaccineLabel.config(text = f'Vaccine: {vaccineCount}%')

错误似乎是 update_Count() 仍在尝试配置不存在的标签。任何帮助将不胜感激!!

错误被抛出是因为 victory_screen 函数破坏了包含 vaccineLabel 的根 window。因此,一旦根被销毁,标签将不再存在,因此您将不再对其使用 .config。

要解决此问题,请在 运行 vaccineLabel.config(text = f'Deaths:{vaccineCount}').

之前检查 vaccineCount < 100

这确保在调用 .config 之前 vaccineLabel 仍然存在。