What's wrong with this tkinter script

What's wrong with this tkinter script

I tried to make a script that gives you a menu for games in tkinter, but if i press Escape then nothing happend, no quit, no error, nothing. This is the script:

from tkinter import Tk, Canvas, Button
import pyautogui as p

root = Tk()

c = Canvas(root, width=400, height=400)

def close(event):
    root2.destroy()

def Game1():
    root.destroy()
    root2 = Tk()
    sx, sy = p.size()
    root2.attributes('-fullscreen', True)
    c2 = Canvas(root2, width=sx, height=sy, bg='green')
    c2.pack()
    root2.bind("<Escape>", close)
    root2.mainloop()

b = Button(root, text='Play (game name 1)', command = Game1)

b.pack()
c.pack()
root.mainloop()

So what's wrong?

i tried doing root2.destroy itself, i tried using other strings in the root2.bind and more

i expect it to close if i press escape

Answer

I've put together a minimal working example showing the proper way to do this with a single root window which is an instance of tk.Tk() and a Toplevel child window were your Canvas lives. As I said, in general it's not necessary (or advisable) to have two instances of Tk in one app.

import tkinter as tk

root = tk.Tk()
c = tk.Canvas(root, width=400, height=400)


def game():
    root.withdraw()  # minimize the root winndow
    game_window = tk.Toplevel(root)  # create game window
    game_window.attributes('-fullscreen', True)
    game_window.bind_all(  # close game on Esc, restore root window
        '<Escape>', lambda _e: [game_window.destroy(), root.deiconify()]
    )  # NOTE: you'll have to click on the window to focus it first
    c2 = tk.Canvas(game_window, bg='green')
    c2.pack()


b = tk.Button(root, text='Play (game name 1)', command=game)

b.pack()
c.pack()
root.mainloop()

Enjoyed this article?

Check out more content on our blog or follow us on social media.

Browse more articles