当函数运行时写入 easygui 文本框?

2023-12-11

我目前正在使用 easygui 运行脚本来接收用户输入。在命令行中运行的旧脚本只会在命令行中打印用户需要知道的任何内容,但我已将其更改为在需要输入时在新的 easygui 框中输出通知。

我想要做的是获得进度,正在运行的函数内的每个操作在完成时打印到文本框中。在命令行中我可以使用print "text"但我无法让它在 easygui 中实时发生。目前,我正在附加一个列表,因此我有一个文本框,可以在一切完成后显示该函数的结果,但我希望在注释过程完成时弹出大文本框窗口并打印该行。这可行吗?

以下是我附加列表的方式:

result_list = []
record_str = "\n Polling has completed for 502."
result_list.append(record_str)
eg.textbox("Polling Status", "Daily polling completion status:", result_list)

我认为没有任何简单的方法可以获得 EasyGUItextbox函数可以做你想做的事情,而不需要修改模块。由于它是一个函数而不是一个类,因此您甚至无法从中派生子类以轻松重用其代码。

然而,创建一个单独的Tkinter窗口,只显示文本行,因为它们是使用我在一个线程中找到的一些代码的增强版本发送给它的comp.lang.python新闻组。

原始代码旨在仅捕获并显示stderrGUI 应用程序的输出通常没有stderr输出句柄,因此该模块被命名为errorwindow。不过我修改了它以便能够重定向两者stderr and stdout到这样的窗口合而为一easygui我开发了基于 - 的应用程序,但我从未抽出时间重命名它或更新其中的评论来提及stdout重定向。;¬)

无论如何,该模块的工作原理是定义和创建名为的类文件类的两个实例OutputPipe当它是imported 并将它们分配给sys.stdout and sys.stderrI/O 流文件对象通常是None在Python中.pywGUI 应用程序(在 Windows 上)。当输出第一次发送到其中任何一个时,同一个模块将作为单独的 Python 进程启动,其stdin, stdout, and stderrI/O 句柄通过原始进程进行管道传输。

发生了很多事情,但如果没有别的事,稍微研究一下可能会给你一些关于如何获得的想法easygui's textbox做你想做的事。希望这可以帮助。

Note:发布的代码适用于 Python 2.x,有一个修改版本可以在 Python 2 和 3 中工作我的答案另一个问题,如果有人感兴趣的话。

File errorwindow.py:

# Code derived from Bryan Olson's source posted in this related Usenet discussion:
#   https://groups.google.com/d/msg/comp.lang.python/HWPhLhXKUos/TpFeWxEE9nsJ
#   https://groups.google.com/d/msg/comp.lang.python/HWPhLhXKUos/eEHYAl4dH9YJ
#
#   Here's a module to show stderr output from console-less Python
#   apps, and stay out of the way otherwise. I plan to make a ASPN
#   recipe of it, but I thought I'd run it by this group first.
#
#   To use it, import the module. That's it. Upon import it will
#   assign sys.stderr.
#
#   In the normal case, your code is perfect so nothing ever gets
#   written to stderr, and the module won't do much of anything.
#   Upon the first write to stderr, if any, the module will launch a
#   new process, and that process will show the stderr output in a
#   window. The window will live until dismissed; I hate, hate, hate
#   those vanishing-consoles-with-critical-information.
#
#   The code shows some arguably-cool tricks. To fit everthing in
#   one file, the module runs the Python interpreter on itself; it
#   uses the "if __name__ == '__main__'" idiom to behave radically
#   differently upon import versus direct execution. It uses TkInter
#   for the window, but that's in a new process; it does not import
#   TkInter into your application.
#
#   To try it out, save it to a file -- I call it "errorwindow.py" -
#   - and import it into some subsequently-incorrect code. For
#   example:
#
#        import errorwindow
#
#        a = 3 + 1 + nonesuchdefined
#
#   should cause a window to appear, showing the traceback of a
#   Python NameError.
#
#   --
#   --Bryan
#   ----------------------------------------------------------------
#
#   martineau - Modified to use subprocess.Popen instead of the os.popen
#               which has been deprecated since Py 2.6. Changed so it
#               redirects both stdout and stderr. Added numerous
#               comments, and also inserted double quotes around paths
#               in case they have embedded space characters in them, as
#               they did on my Windows system.

"""
    Import this module into graphical Python apps to provide a
    sys.stderr. No functions to call, just import it. It uses
    only facilities in the Python standard distribution.

    If nothing is ever written to stderr, then the module just
    sits there and stays out of your face. Upon write to stderr,
    it launches a new process, piping it error stream. The new
    process throws up a window showing the error messages.
"""
import subprocess
import sys
import thread
import os

if __name__ == '__main__':  # when spawned as separate process
    # create window in which to display output
    # then copy stdin to the window until EOF
    # will happen when output is sent to each OutputPipe created
    from Tkinter import BOTH, END, Frame, Text, TOP, YES
    import tkFont
    import Queue

    queue = Queue.Queue(100)

    def read_stdin(app, bufsize=4096):
        fd = sys.stdin.fileno()  # gets file descriptor
        read = os.read
        put = queue.put
        while True:
            put(read(fd, bufsize))

    class Application(Frame):
        def __init__(self, master=None, font_size=8, text_color='#0000AA', rows=25, cols=100):
            Frame.__init__(self, master)
            # argv[0]: name of this script (not used)
            # argv[1]: name of script that imported this module
            # argv[2]: name of redirected stream (optional)
            if len(sys.argv) < 3:
                title = "Output Stream from %s" % (sys.argv[1],)
            else:
                title = "Output Stream '%s' from %s" % (sys.argv[2], sys.argv[1])
            self.master.title(title)
            self.pack(fill=BOTH, expand=YES)
            font = tkFont.Font(family='Courier', size=font_size)
            width = font.measure(' '*(cols+1))
            height = font.metrics('linespace')*(rows+1)
            self.configure(width=width, height=height)
            self.pack_propagate(0)  # force frame to be configured size
            self.logwidget = Text(self, font=font)
            self.logwidget.pack(side=TOP, fill=BOTH, expand=YES)
            # Disallow key entry, but allow copy with <Control-c>
            self.logwidget.bind('<Key>', lambda x: 'break')
            self.logwidget.bind('<Control-c>', lambda x: None)
            self.logwidget.configure(foreground=text_color)
            #self.logwidget.insert(END, '==== Start of Output Stream ====\n\n')
            #self.logwidget.see(END)
            self.after(200, self.start_thread, ())

        def start_thread(self, _):
            thread.start_new_thread(read_stdin, (self,))
            self.after(200, self.check_q, ())

        def check_q(self, _):
            log = self.logwidget
            log_insert = log.insert
            log_see = log.see
            queue_get_nowait = queue.get_nowait
            go = True
            while go:
                try:
                    data = queue_get_nowait()
                    if not data:
                        data = '[EOF]'
                        go = False
                    log_insert(END, data)
                    log_see(END)
                except Queue.Empty:
                    self.after(200, self.check_q, ())
                    go = False

    app = Application()
    app.mainloop()

else: # when module is first imported
    import traceback
    class OutputPipe(object):
        def __init__(self, name=''):
            self.lock = thread.allocate_lock()
            self.name = name

        def __getattr__(self, attr):
            if attr == 'pipe':  # pipe attribute hasn't been created yet
                # launch this module as a separate process to display any output
                # it receives.
                # Note: It's important to put double quotes around everything in case
                # they have embedded space characters.
                command = '"%s" "%s" "%s" "%s"' % (sys.executable,                # command
                                                   __file__,                      # argv[0]
                                                   os.path.basename(sys.argv[0]), # argv[1]
                                                   self.name)                     # argv[2]

                # sample command and arg values on receiving end:
                #   E:\Program Files\Python\python[w].exe                         # command
                #   H:\PythonLib\TestScripts\PyRemindWrk\errorwindow.py           # argv[0]
                #   errorwindow.py                                                # argv[1]
                #   stderr                                                        # argv[2]

                # execute this script as __main__ with a stdin PIPE for sending output to it
                try:
                    # had to make stdout and stderr PIPEs too, to make it work with pythonw.exe
                    self.pipe = subprocess.Popen(command, bufsize=0,
                                                 stdin=subprocess.PIPE,
                                                 stdout=subprocess.PIPE,
                                                 stderr=subprocess.PIPE).stdin
                except Exception:
                    # output exception info to a file since this module isn't working
                    exc_type, exc_value, exc_traceback = sys.exc_info()
                    msg = ('%r exception in %s\n' %
                            (exc_type.__name__, os.path.basename(__file__)))
                    with open('exc_info.txt', 'wt') as info:
                        info.write('msg:' + msg)
                        traceback.print_exc(file=info)
                    sys.exit('fatal error occurred spawning output process')

            return super(OutputPipe, self).__getattribute__(attr)

        def write(self, data):
            with self.lock:
                self.pipe.write(data)  # 1st reference to pipe attr will cause it to be created

    # redirect standard output streams in the process importing the module
    sys.stderr = OutputPipe('stderr')
    sys.stdout = OutputPipe('stdout')
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

当函数运行时写入 easygui 文本框? 的相关文章

随机推荐

  • Mockito WrongTypeOfReturnValue:findById() 无法返回布尔值

    我正在尝试使用 Mockito 通过 JUnit 测试来测试以下方法 Override public List
  • Subversion 与 SourceSafe 的性能对比

    我们是一个由 5 名开发人员组成的分布式团队 致力于相当大的集成项目 我们目前使用 SourceSafe 是的 我know它很糟糕 但直到最近它才起作用 我们一直使用它 我们最近最大的问题变成了性能 签入和签出项目需要很长时间 我们发现自己
  • 我应该输入类型吗?

    创建变量时应该指定类型吗 仅仅声明关键字 var 有什么缺点吗 这两者有什么区别吗 var a 0 int a 0 优点缺点 ONGOING WORK 最佳实践 推荐使用var or final关键字 不指定类型注释 并隐式推断类型已知局部
  • 使用pyHook获取鼠标坐标以便稍后播放

    我正在编写一段代码来使用 pyHook 收集鼠标单击信息 然后使用 win32api 来访问单击函数 本质上 我试图使用鼠标来记录点击模式 以便稍后记录和回放 这是我现在的代码 import win32api win32con time w
  • 如何让网络工作者同时执行多项任务?

    我试图让 Web Worker 管理其状态 同时服务多个异步请求 工人 ts 文件 let a 0 this is my worker s state let worker self as unknown as Worker worker
  • 在 shell 中将星号转义为 Java 命令行参数

    我在 shell 中使用星号作为 Java 命令行参数时遇到了问题 我可以将这个问题的描述简化如下 首先 有一个简单的 java 程序 它打印命令行参数 public class CmdArgsTest public static void
  • C++ long 到 double 的可移植转换

    我需要准确地将长表示位转换为双精度 我的解决方案应可移植到不同的体系结构 能够跨编译器成为标准 如 g 和 clang 也很棒 我正在编写一个快速近似来计算 exp 函数 如建议的那样这个问题的答案 double fast exp doub
  • 使用jquery AJAX提交表单[重复]

    这个问题在这里已经有答案了 我正在尝试使用 jQuery ajax 提交表单 但我的数据没有发布到 PHP 它返回空数组 POST array 这是我的代码 这是我的表格
  • 参数嗅探

    假设我们有一个具有 6 个参数 性能不佳的存储过程 如果六个参数之一传输到存储过程中的局部变量 是否足以禁用参数嗅探 或者是否有必要将传递到存储过程的所有 6 个参数传输到存储过程中的局部变量 根据 Paul White 的评论 将变量分配
  • 如何在中国访问谷歌地图API

    我正在使用 google 地图 api 来获取我的 IBM Mobilefirst 项目中的用户位置 它在除中国之外的所有国家 地区都按预期工作正常 我知道这是因为中国已阻止在其国家 地区访问 google api 是否有任何解决方法我可以
  • 文本到语音转换

    我们正在制作 iPhone 应用程序 客户希望通过语音消息进行提醒 要求是用户设置他们想要提醒的时间和文字 使用文本 我将转换为语音并在触发提醒时播放音频文件 为此 我计划使用谷歌服务 播放这些文本并下载相同的音频文件 NSString u
  • Ruby on Rails - 是否可以通过 /app/assets/images 中的表单保存图像?

    我正在为一家销售二手车的小商店开发一个小型 Rub y on Rails 应用程序 该网站包含所有可用汽车的列表 包括汽车的图像 店内最多有20辆车 我读到 将图像直接保存在数据库中并不是最佳实践 最好使用 Amazon Web Servi
  • 字典格式的键错误“0”

    我仍然是 Python 的初学者 我想知道为什么会这样 dict dict 0 123 a 0 if dict format a format a 1 print True 给我一个关键错误 0 但不是这个 dict dict 0 123
  • 谷歌地图在每个外部链接位置显示多个标记点击而不刷新页面

    我想显示 Google 地图以固定每个位置的多个商店 例如 位置是 Chennai Trichy 班加罗尔 海得拉巴 如果我单击链接钦奈 地图将仅显示钦奈的多个商店 如果我点击 Trichy 链接 地图将仅在 Trichy 中显示多个商店
  • 使用 Outlook 日历 REST API 设置活动组织者

    我正在使用 Outlook REST API 创建事件并发送邀请 基于this文档 我对登录用户进行身份验证 并通过请求的授权标头及其内容上的 json 格式事件发送其承载令牌 如果我将 组织者 设置为另一用户而不是经过身份验证的用户 并将
  • 退出时如何保存 Activity 的状态?安卓

    我有一个基本的应用程序 其中包含文本输入 旋转器输入和第二个旋转器输入 其数组取决于 选项 菜单中更改的设置 目前 当我在应用程序中按 Home 或按 Return 时 我要么返回桌面 要么循环返回最近输入的旧输入 如何防止我的应用程序打开
  • ascx 用户控件中的事件处理

    从用户控件到父控件 页面通信事件的最佳实践是什么我想做类似的事情 MyPage aspx
  • Cordova 插件仅在 iOS 中第二次打开时有效,并出现线程警告。如何让插件初始化 onload?

    我的 iOS 应用程序中的 Cordova 插件仅在您打开应用程序 返回主屏幕将其关闭 然后重新打开应用程序后才起作用 然后 XCode 日志中会显示一条线程警告 2014 05 14 14 00 38 062 TLEMobile 2881
  • EF 4.1 RC:奇怪的级联删除

    我不得不承认 EF 4 1 RC Codefirst DataAnnotations 和 FluentAPI 的功能仍然让我难以抗拒 有时我真的不知道自己在做什么 请参阅以下 POCO public class Country Key pu
  • 当函数运行时写入 easygui 文本框?

    我目前正在使用 easygui 运行脚本来接收用户输入 在命令行中运行的旧脚本只会在命令行中打印用户需要知道的任何内容 但我已将其更改为在需要输入时在新的 easygui 框中输出通知 我想要做的是获得进度 正在运行的函数内的每个操作在完成