首页 > 解决方案 > PySimpleGui:在 GUI 中显示控制台输出

问题描述

我想在 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()

标签: pythonoperating-systempysimplegui

解决方案


嗨在这里找到了答案: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()

推荐阅读