0

I am started to learn python from scratch and not everything is clear to me.

I am trying to make a simple gallery application. When application started - you can browse images (like Next and Previous). All images are named like 1.png, 2.png, etc. and placed in the same folder.

So I am stuck with button. Can't make it change picture. First image is loading successful (1.png), but when I am printing variable Imagecount (just to check it) - it is already equal 2 instead of 1. And nothing happens when button is pressed.

Program is starting without errors. My code is below:

import tkinter
from tkinter import PhotoImage, Tk, Canvas

imagecount = 1  #variable to change file name

class MainUI:

    def change_pic(self, imagecount):  # getting new path to image
        self.filename = r"D:/pic/%d.png" % imagecount
        return (self.filename)

    def clicker(self): # that function should add 1 to variable Imagecount on button click
         global imagecount
         imagecount += 1
         return(imagecount)

    def __init__(self):
        self.windows = Tk()
        self.windows.title("My test gallery")
        self.windows.geometry("1080x720")
        self.windows.minsize(300, 300)
        self.windows.maxsize(1000, 1000)

        self.can = Canvas(self.windows, width=700, height=1000)

        self.icon = PhotoImage(file=self.change_pic(imagecount))  # here I create the
                                                                  # image in this class,
        self.can.create_image(0, 0, anchor='nw', image=self.icon)

        # and there is a button that is not working
        self.button1 = tkinter.Button(self.windows, text="Next", command=self.clicker())
        self.button1.pack()
        self.can.pack()
        self.windows.mainloop()


app = MainUI()

martineau
  • 119,623
  • 25
  • 170
  • 301
  • `command=self.clicker()` calls the function *once*, as your program is starting up, and uses its return value (which is None) as the action to perform when the button is clicked. Get rid of those parentheses, you want to pass the function itself. And you will need to modify the function so that it actually does something - merely changing a global variable is not going to magically redo all of the actions that made use of the variable's previous value. – jasonharper May 18 '22 at 13:18
  • All you currently do when clicking on the button is to change the value of global `imagecount` variable. But that will not update anything else. You need to create a new image with the new filename and add it to the canvas so it can be displayed, and remove the previous image – Anentropic May 18 '22 at 13:18
  • ok, i think i got it - more or less. – Constantine Gorshenin May 18 '22 at 13:49

0 Answers0