Home > other >  Widget.destroy() widget not defined
Widget.destroy() widget not defined

Time:08-30

I have begon making a game with python but i can't get the widget.destroy() to work. It says it is undefined. Here is the log:

Exception in Tkinter callback
Traceback (most recent call last):
  File "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.9/tkinter/__init__.py", line 1892, in __call__
    return self.func(*args)
  File "/data/user/0/ru.iiec.pydroid3/files/temp_iiec_codefile.py", line 12, in start
    title.destroy()
NameError: name 'title' is not defined
from tkinter import Tk, Canvas, Label, Button

class Game():
    def __init__(self):
        self.startscreen()
    def startscreen(self):
        title = Label(root, bg='dark red', text='story game', font=('Arial', 25)).place(x = 150, y = 100)
        startbutton = Button(root, text='start', bg='dark orange', font=('Arial', 15), command=self.start).place(x = 400, y = 1000)
    def start(self):
        title.destroy()
        

cw = 1100
ch = 2200
root = Tk()
c = Canvas(root, bg='dark red',  width=cw, height=ch)
c.pack()
Game()
root.mainloop()

CodePudding user response:

It is undefined, because title is a local variable in the startscreen() function.

Here is the procedural solution.

from tkinter import *
import tkinter as tk

root = tk.Tk()
cw = 600
ch = 600
c = tk.Canvas(root, width=cw, height=ch, bg='dark red')
c.pack()

def main():
    global title
    title = tk.Label(text='Story game', bg='dark red', font=('Arial', 25))
    title.place(relx=0.4, rely=0.2)
    startButton = tk.Button(root, text='Start', bg='dark orange', font=('Arial', 15), command=start)
    startButton.place(relx=0.47, rely=0.5)

def start():
    title.destroy()

main()

root.mainloop()
  • Related