【问题标题】:PySimpleGui: Displaying console output in GUIPySimpleGui:在 GUI 中显示控制台输出
【发布时间】:2020-11-04 12:46:11
【问题描述】:

我想在 Python 中尝试一些 GUI 的东西。我是 Python 和 PySimpleGUI 的新手。我决定制作一个程序,当给定一个 IP 地址时,它会 ping 它并在弹出窗口中显示回复。 (我知道超级简单。)

它工作得很好,但是:它在控制台中显示响应,但我希望它在 GUI 中。

是否可以将控制台输出保存在变量中并以这种方式显示在 GUI 中?

我希望这个问题有意义:)

这是我的代码:

#1 Import:
import PySimpleGUI as sg
import os

#2 Layout:
layout = [[sg.Text('Write the IP-address you want to ping:')],
          [sg.Input(key='-INPUT-')],
          [sg.Button('OK', bind_return_key=True), sg.Button('Cancel')]]
#3 Window:
window = sg.Window('Windows title', layout)

#4 Event loop:
while True:
    event, values = window.read()
    os.system('ping -n 1 {}'.format(values['-INPUT-']))
    if event in (None, 'Cancel'):
        break
        
#5 Close the window:
window.close()

【问题讨论】:

  • PySimpleGUI GitHub 上的演示程序有几个程序可以准确地向您展示如何执行此操作。 Demo_Script_Launcher_Realtime_Output.py 将使用 Popen 启动一个程序,然后在您的窗口中实时显示输出。 Demoi 程序是解决此类问题的绝佳资源。
  • 谢谢@MikeyB - 会检查出来!

标签: python operating-system pysimplegui


【解决方案1】:

您好在这里找到了答案:https://stackoverflow.com/a/57228060/4954813

我一直在用 python 3.9 测试它,就像一个魅力;-)

import subprocess
import sys
import PySimpleGUI as sg

def main():
    layout = [  [sg.Text('Enter a command to execute (e.g. dir or ls)')],
            [sg.Input(key='_IN_')],             # input field where you'll type command
            [sg.Output(size=(60,15))],          # an output area where all print output will go
            [sg.Button('Run'), sg.Button('Exit')] ]     # a couple of buttons

    window = sg.Window('Realtime Shell Command Output', layout)
    while True:             # Event Loop
        event, values = window.Read()
        if event in (None, 'Exit'):         # checks if user wants to 
            exit
            break

        if event == 'Run':                  # the two lines of code needed to get button and run command
            runCommand(cmd=values['_IN_'], window=window)

    window.Close()

# This function does the actual "running" of the command.  Also watches for any output. If found output is printed
def runCommand(cmd, timeout=None, window=None):
    p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    output = ''
    for line in p.stdout:
        line = line.decode(errors='replace' if (sys.version_info) < (3, 5) else 'backslashreplace').rstrip()
        output += line
        print(line)
        window.Refresh() if window else None        # yes, a 1-line if, so shoot me
    retval = p.wait(timeout)
    return (retval, output)                         # also return the output just for fun

if __name__ == '__main__':
    main()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-12
    • 2012-08-22
    • 2020-01-12
    • 1970-01-01
    相关资源
    最近更新 更多