如何解决如何在按钮单击时打开文件 PySimpleGui
我已经在布局中创建了按钮,但我不知道如何在按钮单击时打开 txt 文件。
这是 python,我使用 PySimpleGui 作为框架。
txt 文件很长(~600k 行)所以理想情况下它会在另一个弹出窗口中
在文档和食谱中找不到任何内容
解决方法
在 linux 上,你有一个这样的环境变量,叫做 editor
EDITOR=/usr/bin/micro
您可以使用 os 获取该环境
file_editor = os.getenv("EDITOR",default = "paht/to/default/editor")
然后你可以产生一个进程
os.spawnlp(os.P_WAIT,file_editor,'','/path/to/file')
这本质上是一个弹出窗口。 Windows 可能使用不同的环境名称
离开上面,因为这本质上是这样做的:
os.system('c:/tmp/sample.txt')
上面的代码片段是一个单行代码,基本上可以完成我上面提到的内容
,我不知道你的平台是什么。无论如何,打开文件将涉及:
- 选择要打开的文件(根据您的表述,我了解在您的情况下,它是具有已知路径的给定文件;否则您需要使用,例如
sg.FileBrowse()
);和 - 执行命令以使用默认或指定的阅读器或编辑器打开文件。
我使用以下函数(在 MacOS 和 Windows 中工作)来执行命令:
import platform
import shlex
import subprocess
def execute_command(command: str):
"""
Starts a subprocess to execute the given shell command.
Uses shlex.split() to split the command into arguments the right way.
Logs errors/exceptions (if any) and returns the output of the command.
:param command: Shell command to be executed.
:type command: str
:return: Output of the executed command (out as returned by subprocess.Popen()).
:rtype: str
"""
proc = None
out,err = None,None
try:
if platform.system().lower() == 'windows':
command = shlex.split(command)
proc = subprocess.Popen(command,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE,text=True)
out,err = proc.communicate(timeout=20)
except subprocess.TimeoutExpired:
if proc:
proc.kill()
out,err = proc.communicate()
except Exception as e:
if e:
print(e)
if err:
print(err)
return out
并以这种方式调用它以使用默认编辑器打开文件:
command = f'\"{filename}\"' if platform.system().lower() == 'windows' else \
f'open \"{filename}\"'
execute_command(command)
您可以调整 command
以在您选择的编辑器中打开文件,就像在 CLI 中一样。
这是各种命令的通用解决方案。肯定有更短的解决方案:)
参考:https://docs.python.org/3/library/subprocess.html
,浏览一个txt文件
- 使用
sg.FileBrowse
选择文件并将文件名发送到前一个元素sg.Input
- 设置选项
file_types=(("TXT Files","*.txt"),("ALL Files","*.*"))
ofsg.FileBrowse
以过滤 txt 文件。
读取txt文件
- open(filename,'rt','utf-8') as f
- 阅读来自 f 的所有文本
使用元素 sg.Multiline
创建另一个弹出窗口,其中包含从 txt 文件中读取的文本。
from pathlib import Path
import PySimpleGUI as sg
def popup_text(filename,text):
layout = [
[sg.Multiline(text,size=(80,25)),],]
win = sg.Window(filename,layout,modal=True,finalize=True)
while True:
event,values = win.read()
if event == sg.WINDOW_CLOSED:
break
win.close()
sg.theme("DarkBlue3")
sg.set_options(font=("Microsoft JhengHei",16))
layout = [
[
sg.Input(key='-INPUT-'),sg.FileBrowse(file_types=(("TXT Files","*.*"))),sg.Button("Open"),]
]
window = sg.Window('Title',layout)
while True:
event,values = window.read()
if event == sg.WINDOW_CLOSED:
break
elif event == 'Open':
filename = values['-INPUT-']
if Path(filename).is_file():
try:
with open(filename,"rt",encoding='utf-8') as f:
text = f.read()
popup_text(filename,text)
except Exception as e:
print("Error: ",e)
window.close()
如果txt文件的编码不同,可能会出现问题。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。