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

查看:134
本文介绍了在单独的线程中运行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.

edit:为清楚起见,我只是尝试制作一个将在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天全站免登陆