Hi,

Im having trouble with the piece of code below, i want to have the image change every time you press the button. This code is from a larger project but this is the bit that i cant get to work.

Any ideas?

import Tkinter
import random
import Image, ImageTk

def changeImage():

    listOfImages = ["r7", "A", "C", "B", "b7", "f", "P", "G", "O"]
    im = listOfImages[random.randint(0,8)]
    box1Label.configure(image=im)
    
top = Tkinter.Tk()

r7 = ImageTk.PhotoImage(file="gfx/r7.jpg")
b7 = ImageTk.PhotoImage(file="gfx/b7.jpg")
A = ImageTk.PhotoImage(file="gfx/A.jpg")
B = ImageTk.PhotoImage(file="gfx/B.jpg")
C = ImageTk.PhotoImage(file="gfx/C.jpg")
f = ImageTk.PhotoImage(file="gfx/f.jpg")
G = ImageTk.PhotoImage(file="gfx/G.jpg")
P = ImageTk.PhotoImage(file="gfx/P.jpg")
O = ImageTk.PhotoImage(file="gfx/O.jpg")


box1Label = Tkinter.Label(top, image=r7)
box1Label.grid(row=3, column=2)

changeButton = Tkinter.Button(top, text="Change", command=changeImage)
changeButton.grid(row=9, column=7)

Tkinter.mainloop()

Note that the images are objects not strings, so you have to do this ...

import Tkinter
import random
import Image, ImageTk
 
def changeImage():
    global listOfImages
    im = listOfImages[random.randint(0,8)]
    box1Label.configure(image=im)
    
top = Tkinter.Tk()
r7 = ImageTk.PhotoImage(file="gfx/r7.jpg")
b7 = ImageTk.PhotoImage(file="gfx/b7.jpg")
A = ImageTk.PhotoImage(file="gfx/A.jpg")
B = ImageTk.PhotoImage(file="gfx/B.jpg")
C = ImageTk.PhotoImage(file="gfx/C.jpg")
f = ImageTk.PhotoImage(file="gfx/f.jpg")
G = ImageTk.PhotoImage(file="gfx/G.jpg")
P = ImageTk.PhotoImage(file="gfx/P.jpg")
O = ImageTk.PhotoImage(file="gfx/O.jpg")
# images are objects not strings
listOfImages = [r7, A, C, B, b7, f, P, G, O]
 
box1Label = Tkinter.Label(top, image=r7)
box1Label.grid(row=3, column=2)
changeButton = Tkinter.Button(top, text="Change", command=changeImage)
changeButton.grid(row=9, column=7)
 
Tkinter.mainloop()
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.