John Collins
John Collins

Reputation: 17

tkinter - display random image from array on button click

I would like a label to display a random image when a button is clicked.

This is my approach, but it does not work. Any ideas on how to solve welcome.

from tkinter import *
import random
window = Tk()

filechoices = ["image1.png", "image2.png", "image3.png"]

filename = PhotoImage(file = random.choice[filechoices]) 

def press():    
    image = Label(window, image=filename).pack()

button1 = Button(window, text="click to see image", command = press)
button1.pack()

Upvotes: 0

Views: 600

Answers (1)

jizhihaoSAMA
jizhihaoSAMA

Reputation: 12672

random.choice is a function,not a list.

It should be:

filename = PhotoImage(file = random.choice(filechoices)) 

Read random module

random.choice(seq) Return a random element from the non-empty sequence seq.

Also,in your code,you haven't used mainloop()

Upvotes: 1

Related Questions