首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >PySimpleGui:在图形用户界面中显示控制台输出

PySimpleGui:在图形用户界面中显示控制台输出
EN

Stack Overflow用户
提问于 2020-11-04 20:46:11
回答 1查看 2.4K关注 0票数 0

我想在Python中尝试一些图形用户界面的东西。我是Python和PySimpleGUI的新手。我决定做一个程序,当给定一个IP地址时,它会ping它,并在弹出窗口中显示回复。(我知道非常简单。)

然而,它工作得很好:它在控制台中显示响应,但我想在GUI中显示它。

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

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

这是我的代码:

代码语言:javascript
复制
#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()
EN

回答 1

Stack Overflow用户

发布于 2021-09-05 15:45:40

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

我已经用python 3.9测试过了,它的效果很棒;-)

代码语言:javascript
复制
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()
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64680384

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档