0

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()
acw1668
  • 40,144
  • 5
  • 22
  • 34
  • 2
    You forgot `self`: you should do `self.tile = ...` and `self.title.destroy()` – Robin Dillen Aug 23 '22 at 20:29
  • 1
    Even change `title` to `self.title`, it still has the problem of this [question](https://stackoverflow.com/questions/1101750/tkinter-attributeerror-nonetype-object-has-no-attribute-attribute-name). – acw1668 Aug 24 '22 at 00:47

1 Answers1

1

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()
bePrivate
  • 76
  • 6