python - 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()
解决方案
嗨在这里找到了答案: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()
推荐阅读
- python - 使用 DWT 细节系数创建 2D 图像?
- python - Python:关于pyqt5 QtWebEngineWidgets 如何杀死Qt Qtwebengineprocess进程
- html - 可访问性:将 div 中的多个跨度作为一个句子读出
- google-api - 面对 Google Analytics API 的错误网关
- android - Android的TextView不显示特定数字
- rpmbuild - 如何在我的规范文件中指定 ruby 2.6 模块。我的 rpm 需要 ruby 2.6
- python - 如何在python opencv中简单地裁剪边界框
- python - 在 django 中发帖
- excel - 用vba解析xml
- mysql - Cirrus CI - 无法连接到 MySQL 附加容器