我在写一个程序把图像转换成灰度。我有它良好的工作,现在我实现单选按钮,让用户选择使用哪种类型的灰度。到目前为止,我的问题是,当单选按钮第一次被生成时,command=函数会被立即调用,并将我所有的布尔值设置为True,因为这是我告诉它通过使用function()而不是function来传递的。我在想一种方法,我可以用来存储选中的单选按钮,或者希望有一些内置的东西,我可以做检查。我知道使用全局变量并不是最佳实践,一个类可以消除它们的必要性。这是相关代码。在
# Global variables for radio buttons----
radio1 = False
radio2 = False
radio3 = False
radio4 = False
def whichSelected(numberSelected):
global radio1
global radio2
global radio3
global radio4
if numberSelected == 4:
radio4 = True
if numberSelected == 3:
radio3 = True
if numberSelected == 2:
radio2 = True
if numberSelected == 1:
radio1 = True
# Radio Button Code---------------------------------------------------------
var = tkinter.IntVar()
option1 = tkinter.Radiobutton(window, text ='Average Grayscale',variable = var, value = 1,command = whichSelected(1))
option2 = tkinter.Radiobutton(window, text ='Lightness Grayscale',variable = var, value = 2, command = whichSelected(2))
option3 = tkinter.Radiobutton(window, text ='Luminosity Grayscale',variable = var, value = 3, command = whichSelected(3))
option4 = tkinter.Radiobutton(window, text ='Invert',variable = var, value = 4, command = whichSelected(4))
def change_pixel():
global tkPic2
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:
grayAlgorithm = 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
tkPic2 = ImageTk.PhotoImage(pic, master = window)
print(radio1,radio2,radio3,radio4)
canvas1.create_image(815,170, anchor='e',image = tkPic2)
我不太清楚你为什么首先需要
whichSelected
。您应该能够从var
的值判断:这还有一个额外的好处,可以确保您知道当前检查的值是哪个值。对于前面的方法,您需要添加一些逻辑,以便在生成您想要的全局变量之前将所有全局变量转换为
False
。正如您的函数,如果用户选择一个单选按钮,然后选择另一个,这两个单选按钮都将在全局变量中标记为True
。在然而,指出为什么你的方法也失败是很有启发性的。除了前面提到的问题之外,
command
参数应该是一个函数,您将传递函数的结果(在本例中是None
)。当您调用函数以获得结果时,您将全局参数设置为True
,这是一个副作用。在快速解决方法是使用
^{pr2}$lambda
创建一个新函数,该函数按您想要的方式调用旧函数。这样,您将延迟将全局设置为True
,直到您的单选按钮被实际单击:lambda
对于tkinter
应用程序中的这类事情非常有用。(我无法想象在没有它的情况下编写应用程序…)相关问题 更多 >
编程相关推荐