2016-12-15 123 views
0

我是編程新手,最近開始使用python進行編碼。 我正在編寫一個帶有示例程序代碼的教科書。下面的代碼來自該書,並且根據它們的亮度(它們的RGB值的總和),通過將顏色分配給每個像素黑色或白色,將彩色圖像變成黑白圖像。Python tkinter代碼不起作用

from tkinter import * 
    def black_white(): 
average = 382.5 
for x in range (image.width()): 
    for y in range (image.height()): 
     c = image.get(x, y) 
     brightness = int(c[0]) + int(c[1]) + int(c[2]) 
     if brightness < average: 
      image.put("black", (x)) 
     else: 
      image.put("white", (x)) 

    window = Tk() 
    image = PhotoImage(file="1.gif") 
    button = Button(master=window, command=black_white, 
      font=("Arial", 14), 
      text="Bearbeiten") 

    label = Label(master=window, image=image) 
    label.pack() 
    button.pack(fill=X) 
    window.mainloop() 

然而,該代碼不起作用,該錯誤消息我得到的是:

Exception in Tkinter callback 
    Traceback (most recent call last): 
     File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/tkinter/__init__.py", line 1550, in __call__ 
return self.func(*args) 
     File "/Users/(anonymous)/Desktop/programmieren/raspberry_lehrbuch/schwarzweiß.pyw", line 8, in black_white 
brightness = int(c[0]) + int(c[1]) + int(c[2]) 
    ValueError: invalid literal for int() with base 10: ' ' 

我已經做了一些調查,但無法找到任何東西,使它工作。幫助是非常讚賞:) 哦,我使用的MacBook Pro 2010年埃爾卡皮坦

+0

錯誤表示您嘗試將空字符串轉換爲整數。嘗試'int(「」)',你會得到相同的錯誤信息。在你執行'brightness = int(c [0])+ int(c [1])+ int(c [2])之前檢查'c'' – furas

回答

1

變化(x)(x,y),必須位置x, y

from tkinter import * 


def black_white(): 
    average = 382.5 
    for x in range(image.width()): 
     for y in range(image.height()): 
      c = image.get(x, y) 
      brightness = int(c[0]) + int(c[1]) + int(c[2]) 
      if brightness < average: 
       image.put("black", (x, y)) 
      else: 
       image.put("white", (x, y)) 


window = Tk() 
image = PhotoImage(file="1.gif") 
button = Button(master=window, command=black_white, 
       font=("Arial", 14), 
       text="Bearbeiten") 

label = Label(master=window, image=image) 
label.pack() 
button.pack(fill=X) 
window.mainloop() 

前點擊:

enter image description here

點擊後:

enter image description here