[英]How to change the pixel color of a PhotoImage python
所以我有一個GUI程序,我想根據我制作的rgb滑塊的值更改像素顏色,但我不知道如何更改像素顏色。 我搜尋了大約一個小時,卻找不到任何東西。
from tkinter import *
class Colors(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._image))
self.button.grid(row=1, column=2)
def changeColor(self, image):
red = self.red.get()
blue = self.blue.get()
green = self.green.get()
for y in range(image.height()):
for x in range(image.width()):
image.put()
def main():
Colors().mainloop()
main()
那就是我到目前為止
編輯:我用定義為Fill的方法來完成它,這里是def fill(self):
def fill(self):
"""Fill image with a color=(r,b,g)."""
r, g, b = (self.red.get(), self.green.get(), self.blue.get())
width = self._image.width()
height = self._image.height()
hexcode = "#%02x%02x%02x" % (r, g, b)
horizontal_line = "{" + " ".join([hexcode] * width) + "}"
self._image.put(" ".join([horizontal_line] * height))
我用它代替了我的changeColor方法,效果很好!
首先,您必須在圖像中添加一些內容。 由於您要遍歷每個像素,因此可能需要將滑塊定義的顏色設置為每個像素,如下所示:
image.put("#%02x%02x%02x" % (red, green, blue), (x, y))
接下來是按鈕的定義。 線
self.button = Button(self, text="Change Colors", command=self.changeColor(self._image))
首先執行self.changeColor(self._image)
並將返回值作為參數傳遞給按鈕。 如此處所述,您不能在默認情況下將參數傳遞給command方法,但還介紹了如何規避該方法。
因此,可能的解決方案是這樣的:
from tkinter import *
class Colors(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)
def changeColor(self):
red = self.red.get()
blue = self.blue.get()
green = self.green.get()
for y in range(self._image.height()):
for x in range(self._image.width()):
self._image.put("#%02x%02x%02x" % (red,green,blue), (x, y))
def main():
Colors().mainloop()
main()
由於您逐個像素地更改顏色會花費一些時間,具體取決於您的源圖像,因此您可能希望研究一種通過一次調用設置多個像素的方法。 您可以在tkinter Wiki的PhotoImage頁面中找到一種方法
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.