我正在将Python的Tkinter库用于GUI。
这是初始GUI的图像:
人们输入电子邮件地址并从下拉列表中选择一个选项后,该程序应执行3件事:
我对步骤1没问题,但是我不能同时执行步骤2和3。
方案A(步骤2正常,步骤3正常)
现在,如果更新画布的代码是这样的:
def update(self):
from PIL import Image, ImageTk
global counter
img = ImageTk.PhotoImage(Image.fromarray(self.finish)) # First and maybe second copy.
self.canvas = tkinter.Canvas(self.window, width = img.width(), height = img.height())
self.canvas.pack()
self.canvas.create_image(0, 0, image = img, anchor = tkinter.NW)
self.window.after(1000, self.update())
请注意,在最后一行的self.update()之后有括号。
但是,由于此错误,电子邮件(第3步)未发送:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\ProgramData\Anaconda3\lib\tkinter\__init__.py", line 1705, in __call__
return self.func(*args)
File "C:/Users/SendEmail.py", line 58, in close
self.sendEmail()
File "C:/Users/SendEmail.py", line 278, in sendEmail
self.update()
File "C:/Users/SendEmail.py", line 73, in update
self.window.after(1000, self.update())
File "C:/Users/SendEmail.py", line 73, in update
self.window.after(1000, self.update())
File "C:/Users/SendEmail.py", line 73, in update
self.window.after(1000, self.update())
[Previous line repeated 437 more times]
File "C:/Users/SendEmail.py", line 71, in update
self.canvas.create_image(0, 0, image = img, anchor = tkinter.NW)
File "C:\ProgramData\Anaconda3\lib\tkinter\__init__.py", line 2489, in create_image
return self._create('image', args, kw)
File "C:\ProgramData\Anaconda3\lib\tkinter\__init__.py", line 2480, in _create
*(args + self._options(cnf, kw))))
File "C:\ProgramData\Anaconda3\lib\site-packages\PIL\ImageTk.py", line 139, in __str__
return str(self.__photo)
RecursionError: maximum recursion depth exceeded
我知道递归错误是由于self.update之后的括号引起的。但是,如果我将代码更改为以下代码,情况将相反:
方案B(第2步不正常,第3步不正常)
已更新代码以正确编写回调函数:
def update(self):
from PIL import Image, ImageTk
global counter
img = ImageTk.PhotoImage(Image.fromarray(self.finish)) # First and maybe second copy.
self.canvas = tkinter.Canvas(self.window, width = img.width(), height = img.height())
self.canvas.pack()
self.canvas.create_image(0, 0, image = img, anchor = tkinter.NW)
self.window.after(1000, self.update)
这种编写代码的方式会使画布看起来像这样:
但是,可以发送电子邮件(第3步)。
当我关闭Tkinter窗口时,连接的图像实际上在Spyder控制台上显示出来:
如何在不阻止代码的情况下成功地在画布中更新图像,以便可以发送电子邮件?
感谢您的帮助!