根据你那样改后报错Exception in Tkinter callback Traceback (most recent call last): File "D:\Download\lib\tkinter\__init__.py", line 1921, in __call__ return self.func(*args) File "D:\study\作业\image\main.py", line 278, in <lambda> button3 = Button(root2, text='选择图片', relief=GROOVE, font=('微软雅黑', 14), command=lambda:choosepic()) # 选择图片按钮 File "D:\study\作业\image\main.py", line 263, in choosepic lableShowImage1.destroy() # 删除旧的lableShowImage1 NameError: name 'lableShowImage1' is not defined
时间: 2023-10-07 22:06:05 浏览: 135
这个错误是因为在函数中使用了全局变量`lableShowImage1`,但是在函数调用之前没有对它进行定义。为了解决这个问题,我们需要在全局范围内先定义一个`lableShowImage1`变量,这样才能在函数中使用它。
```
# 在全局范围内定义一个lableShowImage1变量
lableShowImage1 = None
def choosepic():
global lableShowImage1
path_ = tkinter.filedialog.askopenfilename()
path.set(path_)
print(path)
img_open = Image.open(entry.get())
img_array = np.array(img_open)
arr1 = img_array[:]
for x in range(1, arr1.shape[0]):
for y in range(1, arr1.shape[1]):
a = img_array[x, y][0]
b = img_array[x, y][1]
c = img_array[x, y][2]
arr1[x, y] = (a, b, c)
img1 = Image.fromarray(arr1)
img = ImageTk.PhotoImage(img1.resize((380, 330)))
img2 = cv2.resize(arr1, (380, 330), interpolation=cv2.INTER_AREA)
if lableShowImage1:
lableShowImage1.destroy()
lableShowImage1 = Label(root2, bg='#F0E68C', relief=GROOVE, width=380, height=330)
lableShowImage1.config(image=img)
lableShowImage1.image = img
lableShowImage1.place(x=270, y=50)
label4 = Label(text='原始图案', bg='#F0E68C', font=('微软雅黑', 10))
label4.place(x=275, y=38)
os.remove('img.jpg')
cv2.imwrite('img.jpg',img2)
```
在这个修改后的代码中,我们在全局范围内定义了一个`lableShowImage1`变量,并将其初始化为`None`。在函数中,我们首先检查`lableShowImage1`是否存在,如果存在则先使用`destroy()`方法删除它,然后重新生成一个新的`lableShowImage1`。这样就可以避免`lableShowImage1`未定义的错误了。
阅读全文