在单独的线程中运行 Tkinter 表单 [英] Running a Tkinter form in a separate thread

查看:27
本文介绍了在单独的线程中运行 Tkinter 表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个简短的模块,可以传递图像并简单地创建一个 Tkinter 窗口并显示它.我遇到的问题是,即使我在单独的线程中实例化并调用显示图像的方法,主程序也不会继续,直到 Tkinter 窗口关闭.

I have written a short module that can be passed an image and simply creates a Tkinter window and displays it. The problem that I am having is that even when I instantiate and call the method that displays the image in a separate thread, the main program will not continue until the Tkinter window is closed.

这是我的模块:

import Image, ImageTk
import Tkinter


class Viewer(Tkinter.Tk):
    def __init__(self,parent):
        Tkinter.Tk.__init__(self,parent)
        self.parent = parent
        self.initialize()

    def initialize(self):
        self.grid()

    def show(self,img):
        self.to_display = ImageTk.PhotoImage(img)
        self.label_image = Tkinter.Label(self,image=self.to_display)
        self.label_image.grid(column = 0, row = 0, sticky = "NSEW")
        self.mainloop()

它似乎工作正常,除非我从我的测试程序中调用它,如下所示,它似乎不允许我的测试程序继续,即使在不同的线程中启动.

It seems to work fine, except when I call it from my test program like the one below, it will not seem to allow my test program to continue, even when started in a different thread.

import Image
from viewer import Viewer
import threading

def showimage(im):
    view = Viewer(None)
    view.show(im)

if __name__ == "__main__":
    im = Image.open("gaben.jpg")
    t = threading.Thread(showimage(im))
    t.start()
    print "Program keeps going..."

我认为我的问题可能是我应该在模块本身内创建一个新线程,但我想尽量保持简单,因为我是 Python 新手.

I think that perhaps my problem is that I should be creating a new thread within the module itself, but I was wanting to just try and keep it simple, as I am new to Python.

无论如何,提前感谢您的任何帮助.

Anyway, thanks in advance for any assistance.

为了清楚起见,我只是想制作一个将在 Tkinter 窗口中显示图像的模块,以便我可以在任何时候想要显示图像时使用该模块.我遇到的问题是,任何时候程序使用这个模块,它都不能恢复,直到 Tkinter 窗口关闭.

edit: To clarity, I am just trying to make a module that will display an image in a Tkinter window, so that I can use this module any time I want to display an image. The problem that I am having is that any time a program uses this module, it cannot resume until the Tkinter window is closed.

推荐答案

从您的评论来看,您似乎根本不需要 GUI.只需将图像写入磁盘并调用外部查看器即可.

From your comments it sound's like you do not need a GUI at all. Just write the image to disk and call an external viewer.

在大多数系统上,应该可以使用如下方式启动默认查看器:

On most systems it should be possible to launch the default viewer using something like this:

import subprocess 

subprocess.Popen("yourimage.png")

这篇关于在单独的线程中运行 Tkinter 表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆