Caelan Gray
Caelan Gray

Reputation: 9

How to fix "can't invoke button command" in python using tkinter

I'm attempting tkinter in python fo the first time but the Button command creates an error

from tkinter import *
RandomWindow = Tk()
Close = RandomWindow.destroy()
RandomButton = Button(RandomWindow, text = "Click to shuffle and select cards", command = Close)
RandomButton.pack()

It should create a window with a button but I just receive the error message

_tkinter.TclError: can't invoke "button" command: application has been destroyed

Upvotes: 0

Views: 2312

Answers (2)

bruno desthuilliers
bruno desthuilliers

Reputation: 77932

Here:

Close = RandomWindow.destroy() 

you are actually calling the window's destroy method, so when you hit the next line:

RandomButton = Button(RandomWindow, ...)

you are passing an already destroyed window to your button, hence the error.

You want:

Close = RandomWindow.destroy # no parens, just reference the method
RandomButton = Button(
    RandomWindow, 
    text="Click to shuffle and select cards", 
    command=Close
) 

or even more simply:

RandomButton = Button(
    RandomWindow, 
    text="Click to shuffle and select cards", 
    # no parens, just reference the method
    command=RandomWindow.destroy
 ) 

Upvotes: 1

user5407570
user5407570

Reputation:

You already destroyed the window where you assign RandomWindow.destroy() to Close.

Here is what you probably meant:

def Close(): RandomWindow.destroy()

Use that instead of Close = RandomWindow.destroy()

Upvotes: 1

Related Questions