root.after导致全局错误

时间:2014-12-14 12:30:11

标签: python windows python-2.7 tkinter tk

我一直在玩TkInter,但我遇到了让它退出的问题。

我可以显示文字:

from __future__ import absolute_import
from . import BasePlugin
import os, sys
import time
from Tkinter import *


class dis(BasePlugin):

def execute(self, msg, unit, address, when, printer, print_copies):
    mseg = str('%s - %s' % (msg, unit))
    root = Tk()
    text = Text(root, wrap = 'word', bg= 'red', font= 'times 30 bold')
    text.insert(INSERT, msg)
    text.pack()
    root.title('Pager Printer Display')
    root.after(6000, _close)
    root.mainloop(0)


    PLUGIN = dis

但现在我需要在7分钟之后关闭它。

所以我已经厌倦了添加

 def _close():
        root.destroy()

到最后,开始和中间但是得到错误

Global name _close is undefined

e.g

class dis(BasePlugin):
    def _close():
        root.destroy()

    def execute(self, msg, unit, address, when, printer, print_copies):
        mseg = str('%s - %s' % (msg, unit))
        root = Tk()
        text = Text(root, wrap = 'word', bg= 'red', font= 'times 30 bold')
        text.insert(INSERT, msg)
        text.pack()
        root.title('Pager Printer Display')
        root.after(6000, _close)
        root.mainloop(0)

PLUGIN = dis

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:2)

root被定义为局部变量。要使其可以在另一种方法中访问,您应该将其作为实例属性。另外,请不要忘记将_close声明为实例变量。

class dis(BasePlugin):

    def _close(self):
        self.root.destroy()

    def execute(self, msg, unit, address, when, printer, print_copies):
        mseg = str('%s - %s' % (msg, unit))
        self.root = Tk()
        text = Text(self.root, wrap = 'word', bg= 'red', font= 'times 30 bold')
        text.insert(INSERT, msg)
        text.pack()
        self.root.title('Pager Printer Display')
        self.root.after(6000, self._close)
        self.root.mainloop(0)

另一种更简单的方法就是将root.destroy作为回调传递。

class dis(BasePlugin):

    def execute(self, msg, unit, address, when, printer, print_copies):
        mseg = str('%s - %s' % (msg, unit))
        root = Tk()
        text = Text(root, wrap = 'word', bg= 'red', font= 'times 30 bold')
        text.insert(INSERT, msg)
        text.pack()
        root.title('Pager Printer Display')
        root.after(6000, root.destroy)
        root.mainloop(0)