lundi 28 décembre 2020

Pythin tkinter: replace a random image from a list with another one by clicking button

my purpose is to display a random image meal among a list by cliking a button. I already succeed first steps, but what I want is to replace the previous image generated by another one when I click the button again. Currently, all images generated are overlaped (see enter image description here). I have tried many things like canvas.delete("all"), .destroy() and other stuff like that, but nothing works in my case ...

Could you help me ? Here is my code:

import os, random
from tkinter import *


# WINDOW CREATION
window = Tk()
# WINDOW's setup
window.title("Choosing meal")
window.geometry("500x500")
window.config(background = 'blue')

# FIRST BOX QUESTION: 
frame = Frame(window,bg = 'blue')

question_tilte = Label(frame, text = 'Which meal are you going to eat today ?', font = ("Arial",20), bg = 'blue', fg = "white")
question_tilte.pack()
# ADD THE BOX IN THE WINDOW 
frame.pack(expand = YES)

# SECOND BOX CREATION TO PUT THE IMAGE IN:
frame2 = Frame(window, bg = 'blue')

# RANDOM MEAL CHOOSE METHOD:
def choosing_meal():
    if os.path.exists("meals.txt"):
      with open("meals.txt","r") as file:
            meals_list = file.readlines()
            meal_random_choice = random.choice(meals_list)
            print(meal_random_choice)
            file.close()
            # LISTS 
            canvas = [canvas1,canvas2,canvas3,canvas4]
            for i in range(0,len(meals_list)):
                if meal_random_choice == meals_list[i]:
                  canvas[i].grid(row=2,column=1)
    


# MEAL BUTTON GENERATOR :
meal_generator_button = Button(frame, text = "Choose a random meal !", font = ("Helvetica",15), bg = 'white', fg = 'blue', command = choosing_meal)
meal_generator_button.pack(pady = 25, fill = X) # gère les dimensions du bouton

# Image pizza
width = 332
height = 234
image1 = PhotoImage(file = "pizza_fresca.png")
canvas1 = Canvas(frame2,width = width, height = height, bg = "blue", bd = 0,highlightthickness=0)
canvas1.create_image(width/2,height/2, image = image1)

# Image sushis
width2 = 292
height2 = 164
image2 = PhotoImage(file = "sushi.png")
canvas2 = Canvas(frame2,width = width2, height = height2, bg = "blue", bd = 0,highlightthickness=0)
canvas2.create_image(width2/2,height2/2, image = image2) 

# Image crêpes
width3 = 273
height3 = 185
image3 = PhotoImage(file = "crepes.png")
canvas3 = Canvas(frame2,width = width3, height = height3, bg = "blue", bd = 0,highlightthickness=0)
canvas3.create_image(width3/2,height3/2, image = image3)
              
# Image tacos
width4 = 279
height4 = 125
image4 = PhotoImage(file = "tacos.png")
canvas4 = Canvas(frame2,width = width4, height = height4, bg = "blue", bd = 0,highlightthickness=0)
canvas4.create_image(width4/2, height4/2, image = image4)
 
frame2.pack(expand=YES)

# DISPLAY INTERFACE:
window.mainloop()



Aucun commentaire:

Enregistrer un commentaire