- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在开发一个将图像转换为灰度或反转颜色的程序。它使用不同的灰度算法,大多数情况下一切正常,但我有几个问题一直在努力克服。我遇到的一个问题是试图将图像保存出来。为了能够处理不同的文件类型,我使用 PIL 打开图像,然后将其转换为 tk PhotoImage
。现在图像是 PhotoImage
我想不出保存的方法,Tkinter 的文档提到了一种方法,但这失败了。我遇到的另一个问题是我想使用复选框来旋转图像,我有一个函数 rotateIt
可以执行此操作,但是由于 的原因我无法让复选框工作IntVar()
似乎没有改变,请注意我使用 lambda 使其与单选按钮一起使用。 (感谢这里的另一位成员)这是程序的代码。 (我仍在学习,无法弄清楚如何不使用全局变量来完成相同的任务。)
from PIL import Image, ImageTk
from graphics import GraphWin
from tkinter import filedialog # Will be used to open the file from the user
import tkinter
import os
# Global variables for radio buttons----
radio1 = True
radio2 = False
radio3 = False
radio4 = False
#--------------------------------------------
# Global variables for picture-----------
pic = ''
tkPic = ''
tkPic2 = ''
picToConvert = ''
picWidth = 0
picHeight = 0
canvas1 = ''
#---------------------------------------------
def rotateIt(pic1):
pictureRotated = pic1.rotate(180)
return pictureRotated
# Function for radio buttons
def whichSelected(numberSelected):
global radio1
global radio2
global radio3
global radio4
if numberSelected == 4:
radio1 = False
radio4 = True
if numberSelected == 3:
radio1 = False
radio3 = True
if numberSelected == 2:
radio1 = False
radio2 = True
if numberSelected == 1:
radio1 = True
# Gray Algorithms---------------------------------------------
def grayAverage(r,g,b):
algorithm = (r + g + b) // 3
return (algorithm)
def invertRGB(r,g,b):
r = 255 - r
g = 255 - g
b = 255 - b
return (r,g,b)
def lightness(r,g,b):
algorithm = (max(r, g, b) + min(r, g, b)) // 2
return (algorithm)
def luminosity(r,g,b):
algorithm = int(((0.21 * r) + (0.71 * g) + (0.07 * b)))
return (algorithm)
def getRGB(r,g,b):
red = eval( input ("Enter the value of red: "))
green = eval(input ("Enter the value of green: "))
blue = eval(input ("Enter the value of blue: "))
algorithm = red-r + green-g + blue-b // 3
return (algorithm)
# End Gray Algorithms-----------------------------------------------------------------------------
# Draws window, opens picture selected by user, packs the canvas
def drawWindow():
window = tkinter.Tk()
window.title(os.environ.get( "USERNAME" )) # sets the window title to the
return window
def drawCanvas():
global window
global canvas1
canvas1 = tkinter.Canvas(window, width = 820, height =340) # Draws a canvas onto the tkinter window
canvas1.pack()
return canvas1
# Global variables for window and canvas
window = drawWindow()
canvas1 = drawCanvas()
# -----------------------------------------------------------------------------------
# Radio Button Code---------------------------------------------------------
def drawRadioButtons():
global window
var = tkinter.IntVar()
option1 = tkinter.Radiobutton(window, text ='Average Grayscale ',variable = var, value = 1,command = lambda: whichSelected(1))
option2 = tkinter.Radiobutton(window, text ='Lightness Grayscale ',variable = var, value = 2, command = lambda: whichSelected(2))
option3 = tkinter.Radiobutton(window, text ='Luminosity Grayscale ',variable = var, value = 3, command = lambda: whichSelected(3))
option4 = tkinter.Radiobutton(window, text ='Invert',variable = var, value = 4, command = lambda: whichSelected(4))
option1.select() # Sets the first button to clicked
# Pack Radio Buttons
option1.pack(anchor = 'sw')
option2.pack(anchor = 'sw')
option3.pack(anchor = 'sw')
option4.pack(anchor = 'sw')
# End Radio Button code ---------------------------------------------------------
def openImage():
global window
global canvas1
global pic
global picWidth
global picHeight
global tkPic
global tkPic2
global picToConvert
canvas1.delete('all')
del pic
del tkPic
picToConvert = filedialog.askopenfilename(defaultextension='.jpg') # Used to open the file selected by the user
pic = Image.open(picToConvert)
picWidth, picHeight = pic.size # PIL method .size gives both the width and height of a picture
tkPic = ImageTk.PhotoImage(pic, master = window) # Converts the pic image to a tk PhotoImage
canvas1.create_image(10,10,anchor='nw', image = tkPic)
def saveImage():
global pic
global tkPic2
pic = Image.open(tkPic2)
toSave = filedialog.asksaveasfile(mode='w',defaultextension='.jpg')
pic.save(toSave)
def change_pixel():
global window
global canvas1
global tkPic2
global pic
global radio1
global radio2
global radio3
global radio4
# Treats the image as a 2d array, iterates through changing the
#values of each pixel with the algorithm for gray
rgbList = pic.load() #Get a 2d array of the pixels
for row in range(picWidth):
for column in range(picHeight):
rgb = rgbList[row,column]
r,g,b = rgb # Unpacks the RGB value tuple per pixel
if radio1 == True:
grayAlgorithm1 = grayAverage(r,g,b)
rgbList[row,column] = (grayAlgorithm1, grayAlgorithm1, grayAlgorithm1)
elif radio2 == True:
grayAlgorithm1 = lightness(r,g,b)
rgbList[row,column] = (grayAlgorithm1, grayAlgorithm1, grayAlgorithm1)
elif radio3 == True:
grayAlgorithm1= luminosity(r,g,b)
rgbList[row,column] = (grayAlgorithm1, grayAlgorithm1, grayAlgorithm1) # Gives each pixel a new RGB value
elif radio4 == True:
r,g,b= invertRGB(r,g,b)
rgbList[row,column] = (r, g, b) # Gives each pixel a new RGB value
# Converting to a tkinter PhotoImage
del tkPic2
tkPic2 = ImageTk.PhotoImage(pic, master = window)
canvas1.create_image(815,170, anchor='e',image = tkPic2)
# Function to create a button, takes the button text and the function to be called on click
def tkButtonCreate(text, command):
tkinter.Button(window, text = text, command = command).pack()
def main():
drawRadioButtons()
tkButtonCreate('Open Image',openImage)
tkButtonCreate('Convert', change_pixel)
tkButtonCreate('Save',saveImage)
window.mainloop()
#convertButton = tkinter.Button(window,text = 'Convert', command = change_pixel).pack()
main()
最佳答案
删除 pic = Image.open(tkPic2)
在 saveImage()
保存文件使用:
def saveImage():
global pic
toSave = filedialog.asksaveasfile(mode='w',defaultextension='.jpg')
pic.save(toSave)
顺便说一句:为了更好地使用对象 None
代替 ''
pic = None
tkPic = None
tkPic2 = None
picToConvert = None
canvas1 = None
此外,del
给你None
del tkPic2 # now tkPic2 == None
编辑: IntVar 和旋转问题的解决方案。
我创建全局变量 var = None
然后我可以在函数中使用它(使用 global var
)
我使用 pic = pic.rotate(180)
在没有新变量的情况下“就地”旋转。
我为 Rotation
添加单选按钮和功能onConvert
运行 rotateIt
或 change_pixel
现在我创建 tkPic2
在 onConvert
from PIL import Image, ImageTk
#from graphics import GraphWin # not needed
# for Python 3.x
from tkinter import filedialog # Will be used to open the file from the user
import tkinter
# for Python 2.x
#import Tkinter as tkinter
#import tkFileDialog as filedialog # Will be used to open the file from the user
import os
# --- Global variables for radio buttons ---
radio1 = True
radio2 = False
radio3 = False
radio4 = False
#--------------------------------------------
# --- Global variables for picture ---
pic = None
tkPic = None
tkPic2 = None
picToConvert = None
picWidth = 0
picHeight = 0
canvas1 = None
var = None #create global variable
#----------------------------------------------------------------------
def rotateIt():
global pic
print "(debug) rotateIt:", pic
pic = pic.rotate(180)
# --- Function for radio buttons ---
def whichSelected(numberSelected):
global radio1
global radio2
global radio3
global radio4
if numberSelected == 4:
radio1 = False
radio4 = True
elif numberSelected == 3:
radio1 = False
radio3 = True
elif numberSelected == 2:
radio1 = False
radio2 = True
elif numberSelected == 1:
radio1 = True
# --- Gray Algorithms ---
def grayAverage(r, g, b):
return (r + g + b) // 3
def invertRGB(r,g,b):
return (255 - r, 255 - g, 255 - b)
def lightness(r,g,b):
return (max(r, g, b) + min(r, g, b)) // 2
def luminosity(r,g,b):
return int(((0.21 * r) + (0.71 * g) + (0.07 * b)))
def getRGB(r,g,b):
red = eval(input("Enter the value of red: "))
green = eval(input("Enter the value of green: "))
blue = eval(input("Enter the value of blue: "))
return red-r + green-g + blue-b // 3
# --- End Gray Algorithms ---
# Draws window, opens picture selected by user, packs the canvas
def drawWindow():
window = tkinter.Tk()
window.title(os.environ.get( "USERNAME" )) # sets the window title to the
return window
def drawCanvas():
global window
global canvas1
canvas1 = tkinter.Canvas(window, width = 820, height =340) # Draws a canvas onto the tkinter window
canvas1.pack()
return canvas1
# Global variables for window and canvas
window = drawWindow()
canvas1 = drawCanvas()
#----------------------------------------------------------------------
# --- Radio Button Code ---
def drawRadioButtons():
global window, var
var = tkinter.IntVar()
option1 = tkinter.Radiobutton(window, text ='Average Grayscale', variable = var, value = 1, command = lambda: whichSelected(1))
option2 = tkinter.Radiobutton(window, text ='Lightness Grayscale', variable = var, value = 2, command = lambda: whichSelected(2))
option3 = tkinter.Radiobutton(window, text ='Luminosity Grayscale', variable = var, value = 3, command = lambda: whichSelected(3))
option4 = tkinter.Radiobutton(window, text ='Invert', variable = var, value = 4, command = lambda: whichSelected(4))
option5 = tkinter.Radiobutton(window, text ='Rotate 180', variable = var, value = 5)
# Sets the first button to clicked
option1.select()
# Pack Radio Buttons
option1.pack(anchor = 'sw')
option2.pack(anchor = 'sw')
option3.pack(anchor = 'sw')
option4.pack(anchor = 'sw')
option5.pack(anchor = 'sw')
# End Radio Button code
def openImage():
global window
global canvas1
global pic
global picWidth
global picHeight
global tkPic
global tkPic2
global picToConvert
canvas1.delete('all')
del pic
del tkPic
picToConvert = filedialog.askopenfilename(defaultextension='.jpg') # Used to open the file selected by the user
pic = Image.open(picToConvert).convert('RGB')
picWidth, picHeight = pic.size # PIL method .size gives both the width and height of a picture
tkPic = ImageTk.PhotoImage(pic, master = window) # Converts the pic image to a tk PhotoImage
canvas1.create_image(10,10,anchor='nw', image = tkPic)
#----------------------------------------------------------------------
def saveImage():
global pic
toSave = filedialog.asksaveasfile(mode='w',defaultextension='.jpg')
pic.save(toSave)
#----------------------------------------------------------------------
def onConvert():
global var
global tkPic2
global window
if var.get() == 5:
rotateIt(pic)
else:
change_pixel()
# Converting to a tkinter PhotoImage
if tkPic2:
del tkPic2
tkPic2 = ImageTk.PhotoImage(pic, master = window)
canvas1.create_image(815,170, anchor='e',image = tkPic2)
#----------------------------------------------------------------------
def change_pixel():
global window
global canvas1
global pic
global radio1
global radio2
global radio3
global radio4
# Treats the image as a 2d array, iterates through changing the
#values of each pixel with the algorithm for gray
rgbList = pic.load() #Get a 2d array of the pixels
for row in range(picWidth):
for column in range(picHeight):
rgb = rgbList[row,column]
#print rgb
r,g,b = rgb # Unpacks the RGB value tuple per pixel
if radio1 == True:
grayAlgorithm1 = grayAverage(r,g,b)
rgbList[row,column] = (grayAlgorithm1, grayAlgorithm1, grayAlgorithm1)
elif radio2 == True:
grayAlgorithm1 = lightness(r,g,b)
rgbList[row,column] = (grayAlgorithm1, grayAlgorithm1, grayAlgorithm1)
elif radio3 == True:
grayAlgorithm1= luminosity(r,g,b)
rgbList[row,column] = (grayAlgorithm1, grayAlgorithm1, grayAlgorithm1) # Gives each pixel a new RGB value
elif radio4 == True:
rgbList[row,column] = invertRGB(r,g,b) # Gives each pixel a new RGB value
#----------------------------------------------------------------------
# Function to create a button, takes the button text and the function to be called on click
def tkButtonCreate(text, command):
tkinter.Button(window, text = text, command = command).pack()
#----------------------------------------------------------------------
def main():
drawRadioButtons()
tkButtonCreate('Open Image',openImage)
tkButtonCreate('Convert', onConvert)
tkButtonCreate('Save',saveImage)
window.mainloop()
#convertButton = tkinter.Button(window,text = 'Convert', command = change_pixel).pack()
#----------------------------------------------------------------------
main()
关于python-3.x - 在将 tk PhotoImage 转换回 PIL 图像以保存时遇到一些问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20448568/
我想向 tk.Tk 和 tk.Toplevel 的实例添加 2 个方法。前者作为应用程序根窗口存在,后者由用户创建任意次数。每个 tk.Toplevel 代表应用程序的不同功能,目前有 13 种变体。
尝试创建 Listbox 的子类,以便我可以创建一个新的 KeyListbox from tkinter import * class KeyListbox(Listbox): def __
以下是错误: $ perl ftper.plUse of uninitialized value $id in hash element at /usr/lib/perl5/vendor_perl/5
我正在尝试使用 tk.Scale 来更改 tk.IntVar。我可以在第一个 tk 窗口上执行此操作,但不能在第二个窗口上执行。为什么? 看看这个可怜的样本: import tkinter as tk
我输入了我的框架比例,但我不确定如何在我的标签中显示这个比例的值。每次秤移动时我都需要更新它。我怎样才能做到这一点? self.options_settings.framepripojeni6 = F
这个video向我介绍了 X 的问题以及 Wayland 协议(protocol)的替代方案。多年来,Wayland 协议(protocol)的采用似乎在不断增长。 我的问题: tkinter 和 t
这些天我经常看到这一行:tk.Tk.__init__(self,*args,**kwargs)并且不明白它的用途。我的问题不是 *args 和 **kwargs)。 例如,在此处的这些代码行中: cl
这个问题涉及Python和Tkinter。 我想同时使用两个不同的 ttk 主题,例如一个 Tkinter 窗口中的“clam”和“vista”。所以我写了这个: import tkinter as
从 Tk 8.5 开始,Tk 开始使用基于原生的 UI 组件——按钮、滚动条等。我想知道 C++/Tk 是否支持这种原生 GUI 方法? 最佳答案 据我所知,C++/Tk 是基于 Tk 8.4(如果是
我无法让 ruby 成功地 require 'tk'。我正在使用 rvm、ruby 2.0.0、ActiveTcl-8.6 和 Ubuntu 12.04 LTS。我已经运行了随 ActiveTcl
我想用最有效的方式来限制用户不输入数字以外的任何内容。例如:当他们在条目中输入字母时,该条目将被清除。有没有什么方法可以用最少的结构改变来做到这一点? 这是我的代码:[??????标志是我被困的地方]
我真的很喜欢Perl/Tk ,但已经得出的意见认为它是 DOA。我认为 Tcl::Tk和 Tkx是更好的解决方案。假设我放弃 Perl/Tk . Tcl::Tk 是“最受支持”的路线吗? (自 200
我正在尝试使用 perl:latest 和 activestate/circleci-activeperl:latest 图像在 ubuntu:16.04 容器上运行使用 Tk 模块制作的简单 per
我曾经使用 tk.Scale 的 digits 属性来确保 Label 或 Spinbox 中的数字> 在 slider 移动时显示固定的小数位数。比如 3.456, 4444.567, 555555
问题就在标题中,本质上是:如何在设置 Entry 的 textvariable 后继续调用 validatecommand 回调?这是最低工作示例 (MWE): import tkinter as t
在Perl/Tk应用程序中,我想将带有任意Unicode文件名的文件拖放到小工具上。。有一个正在运行的DropSite示例:Windows资源管理器中的perl tk拖放文件夹,但它不能处理包含Uni
我在 macOS BigSur 上通过 VMWare 使用 Ubuntu 20.04.2 LTS。我安装了最新版本的 tcl、tcl-dev、tk 和 tk-dev - 版本 8.6。我想编译 Arc
我组装 Tk 窗口的方式有问题(在 Win XP 下使用 R tcltk 和 tcltk2) library(tcltk) library(tcltk2) expandTk <- function()
我想在 Textdocument 的特定行中写入,但我的代码有问题,我不知道错误在哪里。 set fp [open C:/Users/user/Desktop/tst/settings.txt w]
当在 TK 中创建新的顶层或按钮时,需要输入路径名。我看过一个基本代码,如下所示: toplevel .a ... button .a.b ... 我的问题是:点与字母的处理方式是否不同?它们是某种创
我是一名优秀的程序员,十分优秀!