Skip to content Skip to sidebar Skip to footer

How To Change The Pixel Color Of A Photoimage Python

So i have a program for gui i want to change the pixel color based on the values of the rgb sliders i made, I can't figure out how to change the pixel colors. I searched for like a

Solution 1:

First of all, you have to put something into the image. Since you are iterating over every pixel you probably want to set the color defined by the sliders into every pixel, like so:

image.put("#%02x%02x%02x" % (red, green, blue), (x, y))

The next thing is the definition of your button. The line

self.button = Button(self, text="Change Colors", command=self.changeColor(self._image))

first executes self.changeColor(self._image) and passes the return value as a parameter to the button. As described here you cannot pass parameters to the command method by default but also describes how to circumvent that.

So a possible solution would be something like this:

from tkinter import *

classColors(Frame):
    def__init__(self):
        Frame.__init__(self)
        self._image = PhotoImage(file="r.gif")
        self._imageLabel = Label(self, image=self._image)
        self._imageLabel.grid()

        self.master.title("Color Changer")
        self.grid()

        self.red = Scale(self, from_=0, to=255, label="Red", fg="red", )
        self.red.grid(row=0, column=1)

        self.green = Scale(self, from_=0, to=255, label="Green", fg='green')
        self.green.grid(row=0, column=2)

        self.blue = Scale(self, from_=0, to=255, label="Blue", fg="blue")
        self.blue.grid(row=0, column=3)

        self.button = Button(self, text="Change Colors", command=self.changeColor)
        self.button.grid(row=1, column=2)

    defchangeColor(self):
        red = self.red.get()
        blue = self.blue.get()
        green = self.green.get()
        for y inrange(self._image.height()):
            for x inrange(self._image.width()):
                self._image.put("#%02x%02x%02x" % (red,green,blue), (x, y))

defmain():
    Colors().mainloop()

main()

Since you change the color pixel by pixel this takes some time depending on your source image, you might want to look at ways to set more than one pixel with one call. You can find a way in the PhotoImage page of the tkinter wiki

Post a Comment for "How To Change The Pixel Color Of A Photoimage Python"