0

I'm trying to change the image of a TKinter button through a function. The result that I get is that the button just turns into a blank button when I change the image. Does anybody know the right way to do this?

I attached the images I used for my program.

gray q image

green q image

from tkinter import *
from PIL import ImageTk, Image


#Create main window of program and sizes the window
root = Tk()
root.geometry("485x700")
root.configure(bg="#24F086")


#Creates entry widget
e = Entry(root)
e.place(rely=.78, relx=.50, anchor="center")

#Functions for keyboard

#Puts text in the entry widget
def insertion(string):

    e.insert("end", string)


#Submits the text in the entry widget to a function
def entryEnter():

    
    theInput = e.get()

    guess(theInput)

#Modifies the Q key's image based on if the user types the right input
def guess(answer):


    if answer == "qqqqq":

        keyLocation = "green-" + 'q' + "-key.png"
        qKeyLetter = ImageTk.PhotoImage(Image.open(keyLocation)) 
        qKeyButton.configure(image = "")
        qKeyLetter = ImageTk.PhotoImage(Image.open(keyLocation)) 
        qKeyButton.configure(image = qKeyLetter)
                
    else:

        pass
        


#Buttons for the keyboard are below
global qKeyLetter
qKeyLetter = ImageTk.PhotoImage(Image.open("gray-q-key.png"))
qKeyButton = Button(root, image=qKeyLetter, cursor="hand2", highlightthickness=2, highlightbackground="black", command=lambda: insertion('q'))
qKeyButton.place(rely=.85, relx=.14, anchor="center")


enterKeyButton = Button(root, text="ENTER", cursor="hand2", highlightthickness=2, highlightbackground="black", command=entryEnter)
enterKeyButton.place(rely=.95, relx=.14, anchor="center")


root.mainloop()



Tried: Making both the qKeyLetter and the qKeyButton global

Expected: To access those variables properly in the guess function

Happened: The guess function just removed the original image on the qKeyButton and didn't replace it with anything.

Tried: Moving the qKeyButton and qKeyLetter definitions above the guess function

Expected: To access those variables properly in the guess function

Happened: The guess function just removed the original image on the qKeyButton and didn't replace it with anything.

MrRunIt82
  • 23
  • 1
  • 5

0 Answers0