Search code examples
pythonpython-3.xtkinterlabelwindow

invalid command name ".!label3"


I am creating a game where when the vaccine reaches 100, the game finishes, and the user is transferred to a victory screen. See below

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()

This brought me an error. When I destroy the window and create a new one, the new window displays. However, for some reason an error occurred in these lines with error type invalid command name ".!label3"

The lines which contained the errors are below:

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

The error seems to be that update_Count() is still trying to configure a label that doesn't exist. Any help would be much appreciated!!


Solution

  • The error is being thrown because the victory_screen function destroys the root window which contains the vaccineLabel. As a result, once the root is destroyed the Label no longer exists and so you are no longer to use .config on it.

    To fix this, check if the vaccineCount < 100 before you run vaccineLabel.config(text = f'Deaths:{vaccineCount}').

    This ensures that the vaccineLabel still exists before calling .config on it.