【问题标题】:How can i reload a picture with Tkinter after GPIO button press?按下 GPIO 按钮后如何使用 Tkinter 重新加载图片?
【发布时间】:2016-06-21 21:58:25
【问题描述】:

我有以下基于另一个 Stackoverflow 问题的解决方案的脚本。我有一个 tkinter GUI,其中有一张在拍摄新照片时应该刷新的图片。

class App(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.start()

    def callback(self):
        self.root.quit()

    def run(self):
        self.root = Tk()
        self.root.geometry("{0}x{1}+0+0".format(800,800))

        files = sorted(os.listdir(os.getcwd()),key=os.path.getmtime)

        Label(self.root,image = ImageTk.PhotoImage(Image.open(files[-1]).resize((300, 200)))).grid(row = 1, column = 0)

        Label(self.root, text=files[-1]).grid(row=0, column=0)
        self.root.mainloop()

    def update(self):

        files = sorted(os.listdir(os.getcwd()),key=os.path.getmtime)

        img1 = self.ImageTk.PhotoImage(self.Image.open(files[-1]).resize((300, 200)))
        Label(self.root,image = img1).grid(row = 1, column = 0)

        Label(self.root, text=files[-1]).grid(row=0, column=0)

        self.root.update()

app = App()        
app.update()

我收到此错误:

Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/PIL/ImageTk.py", line 176, in paste
    tk.call("PyImagingPhoto", self.__photo, block.id)
_tkinter.TclError: invalid command name "PyImagingPhoto"

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "./mainloop.py", line 98, in <module>
    app.update()
  File "./mainloop.py", line 79, in update
    img1 = ImageTk.PhotoImage(Image.open(files[-1]).resize((300, 200)))
  File "/usr/lib/python3/dist-packages/PIL/ImageTk.py", line 115, in __init__
    self.paste(image)
  File "/usr/lib/python3/dist-packages/PIL/ImageTk.py", line 182, in paste
    _imagingtk.tkinit(tk.interpaddr(), 1)
OverflowError: Python int too large to convert to C ssize_t

我做错了什么?使用文件名创建标签确实有效。文件名是有效文件。当脚本不在 thread.Threading 部分内时,它确实可以工作。当按下 Raspberry GPIO 按钮时,我想用最新的图片更新屏幕(脚本将用相机拍摄一张新照片)。所以屏幕应该会加载最新拍摄的照片。

【问题讨论】:

    标签: python python-3.x tkinter raspberry-pi gpio


    【解决方案1】:

    tkinter 不是线程安全的(默认情况下)。所有处理 GUI 的操作都必须在主线程中完成。您可以使用事件回调来做您所要求的事情,但是除非您实现一个馈入主循环的事件队列,否则线程可以并且将会破坏 tkinter。

    此外,堆栈跟踪似乎指向的不是您的代码 - 堆栈跟踪根本不与呈现的代码相交。

    另外,调用 root.update() 通常是一个坏主意——它会启动另一个本地事件循环,它可能能够为另一个事件循环调用另一个 root.update() 并无限循环。 root.update_idletasks() 比完整的 root.update() 更安全

    【讨论】:

      猜你喜欢
      • 2016-03-18
      • 2015-07-12
      • 2020-05-22
      • 2020-10-21
      • 2011-06-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-10
      相关资源
      最近更新 更多