Reputation: 4357
I have a dropdown menu with a couple of choices and a label with an image in it.
I would like to change the image according to the choice selected from the dropdown menu,but i cant figure it out.
Example code:
from Tkinter import*
import Tkinter as tk
def image():
list1=['im1.gif','im2.gif']
studDropDown['menu'].delete(0, "end")
for string in list1:
studDropDown['menu'].add_command(label=string,command=lambda value=string:studFiles.set(value))
app=Tk()
app.title("Example")
app.geometry('500x200+200+200')
app.configure(background='black')
app.resizable(0,0)
button1=Button(app,text='Press me',command=image)
button1.pack()
studFiles = StringVar()
studFiles.set('Image')
files =["Please Wait"]
studDropDown = OptionMenu(app, studFiles, *files)
studDropDown.config(font=("Times",16,"italic"))
studDropDown["menu"].config(font=("Times",16,"italic"))
studDropDown.pack()
photo =PhotoImage(file='im.gif')
label = Label(app,image=photo)
label.image = photo # keep a reference!
label.pack()
app.mainloop()
Maybe even the use of label to display an image is not suitable.
Any ideas ?
Upvotes: 2
Views: 8691
Reputation: 5760
Here is a simple example based of the code you provided:
from Tkinter import *
def change_image(*args):
# Change image of label accordingly
label.config(image=photos[int(studFiles.get())])
app = Tk()
app.title("Example")
app.geometry('500x200+200+200')
app.configure(background='black')
app.resizable(0,0)
studFiles = StringVar()
studFiles.set('Image')
files =['0', '1'] # Number is corresponding list index
studDropDown = OptionMenu(app, studFiles, *files)
studDropDown.config(font=("Times", 16, "italic"))
studDropDown["menu"].config(font=("Times", 16, "italic"))
studDropDown.pack()
studFiles.trace("w", change_image)
# List of photoimages for each image
photos =(PhotoImage(file='im.gif'), PhotoImage(file='im2.gif'))
label = Label(app,image=photos[0])
label.pack()
app.mainloop()
You have to make a list/tuple of PhotoImage
s for every graphic you want. You also have to trace your StringVar
, so you know when the value of the OptionMenu
has changed. Then all you have to do is set the image of the label with the config
method.
Upvotes: 7