0

I am working on a picture thing, and I want the user to be able to select an image with buttons. But instead, nothing changes. How do you do that?

import tkinter as tk
from PIL import ImageTk, Image
n = 0
x = 0
def func(n):
    is_ = [
        Image.open(r"image_file1.png"),
        Image.open(r"image_file2.png"),
        Image.open(r"image_file3.png")
    ]
    global x
    x = n
    i2 = ImageTk.PhotoImage(is_[x])
    c2.create_image(50, 50, image = i2)
    
root = tk.Tk()
i = Image.open(r"C:\Users\User\Desktop\0mega.patch\2. Python\LucasPatrykRiley\Pfps\Clear Background.png")
i2 = ImageTk.PhotoImage(i)


c = tk.Canvas(root, height = 600, width = 600)
c.pack()

f = tk.Frame(root)

c2 = tk.Canvas(f, height = 100, width = 100, bg = "Blue")
c2.create_image(50, 50, image = i2)
c2.pack()

b = tk.Button(f, text = ">", command = func(x + 1))
b.pack()

b2 = tk.Button(f, text = "<", command = func(x - 1))
b2.pack()


c.create_window(200, 500, window = f)

root.mainloop()

is_ is the list of all images;
x is the user choice which gets updated so you can take the previous / next image;
c is the canvas where everything is positioned. I chose canvas bc the canvas can contain images.
This is a snippet of the main file, where the canvas has an image of the actual background.
The widgets are packed into the f Frame, which get placed into the c canvas

How can I make the images change with the button press?

Matiiss
  • 5,203
  • 2
  • 11
  • 27
Katalysmus
  • 41
  • 7
  • 1
    Why do You ask `can` and not `how` because in vast majority of cases the answer to `can` is YES. And so in this case. The answer to _Can you change the picture in a gui with a button press?_ is YES. Anyhow 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) – Matiiss May 14 '21 at 13:18
  • Just so You know, Labels and Buttons can too contain images. And I think it would be actually maybe easier to change an image for a label than canvas – Matiiss May 14 '21 at 13:21
  • The issue: You create all the images in a function and when the function is done that list that contained all those images gets garbage collected and since no reference was created it all gets deleted. See previous comment for a similar issue. – Matiiss May 14 '21 at 13:27
  • 1
    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) – Matiiss May 14 '21 at 13:27

0 Answers0