0

Using Tkinter. When I click my button, I want it to display the image which is the same as the randomised number. That works fine as it tells me in the shell what image it is choosing, however all I see on my screen is a white box.

This the part of the code that isn't working:

def hide_previous(event):  #works fine
    rolling_lbl.place_forget()
    d1.place_forget()
def roll_dice(): #works fine - gets the randomised dice
    global dice_sides
    number = random.randint(1,(dice_sides))
    diceimg1= "Resources/Dice_imgs/dice_img_"+str(number) +".png"
    return diceimg1
    
def update_dice(event): # code with the issue
    if no_dice == 1:
        window.update()
        myimg = roll_dice()
        updated_picture = ImageTk.PhotoImage(Image.open(myimg))
        d1.place(x=310 ,y=255)
        d1.configure(image = updated_picture)
        print(myimg) # tells shell what image is being displayed for testing purposes



roll=Button(window, text="Roll the Dice", background="red", fg="white", activebackground='cyan',font=("Calibri",(30)), width =180, height = 55, borderless=1)
roll.place(x=350, y=120)
roll.bind('<Button-1>', hide_previous, add="+") #hides previous label/image
roll.bind('<Button-1>', rolled_lbl, add="+") #label that works fine
roll.bind('<Button-1>', update_dice, add="+")
myimg = roll_dice()
dc1 = ImageTk.PhotoImage(Image.open(myimg))
d1=Label(window, image = dc1)
d1.place(x=345, y=295)
d1.place_forget() # had to implement because dice will show from beginning

The weird part about all of this was that when I had a resize config such as below, it worked fine but provided an error in the shell. (got rid of the resize and left antialias)

def update_dice(event):
    if no_dice == 1:
        window.update()
        myimg = roll_dice()
        updated_picture = ImageTk.PhotoImage(Image.open(myimg))
        d1.place(x=310 ,y=255)
        d1.configure(image = updated_picture)
        d2=d1.configure( Image.ANTIALIAS)
        print(myimg)
mcsoini
  • 6,280
  • 2
  • 15
  • 38
pesto_23
  • 11
  • 4
  • 5
    Does this answer your question? [Why does Tkinter image not show up if created in a function?](https://stackoverflow.com/questions/16424091/why-does-tkinter-image-not-show-up-if-created-in-a-function) – Art Aug 18 '21 at 01:31
  • @Art Thank you so much it worked!!! I hate how this one word can make or break the code! – pesto_23 Aug 18 '21 at 01:44

0 Answers0