如何在按钮单击时打开文件 PySimpleGui

如何解决如何在按钮单击时打开文件 PySimpleGui

我的目标是创建一个按钮,并在按下按钮时打开 txt 文件

我已经在布局中创建了按钮,但我不知道如何在按钮单击时打开 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","*.*")) of sg.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 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?
Java在半透明框架/面板/组件上重新绘画。
Java“ Class.forName()”和“ Class.forName()。newInstance()”之间有什么区别?
在此环境中不提供编译器。也许是在JRE而不是JDK上运行?
Java用相同的方法在一个类中实现两个接口。哪种接口方法被覆盖?
Java 什么是Runtime.getRuntime()。totalMemory()和freeMemory()?
java.library.path中的java.lang.UnsatisfiedLinkError否*****。dll
JavaFX“位置是必需的。” 即使在同一包装中
Java 导入两个具有相同名称的类。怎么处理?
Java 是否应该在HttpServletResponse.getOutputStream()/。getWriter()上调用.close()?
Java RegEx元字符(。)和普通点?