【问题标题】:root.after causes Global errorroot.after 导致全局错误
【发布时间】:2015-02-12 16:17:59
【问题描述】:

我一直在玩 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

例如

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

有人可以帮忙吗?

【问题讨论】:

    标签: python windows python-2.7 tkinter tk


    【解决方案1】:

    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)
    

    【讨论】:

    • 干杯底部一个工作了一个款待。我发誓我已经尝试过了,但我可能对此感到非常沮丧:)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-09
    • 1970-01-01
    • 1970-01-01
    • 2012-12-29
    • 1970-01-01
    • 2022-10-20
    • 2015-08-31
    相关资源
    最近更新 更多