【问题标题】:Windows "Command Prompt" inside tkinter frametkinter 框架内的 Windows“命令提示符”
【发布时间】:2019-01-26 12:03:25
【问题描述】:

如何在 tkinter 框架内运行命令提示符?我知道如何使用“pygame”,但这些方法不起作用 - 命令提示符只是在另一个窗口中运行。

我试着这样做:

import tkinter as tk
import os
import subprocess

root = tk.Tk()
root.geometry("640x480")
frame = tk.Frame(root)
frame.pack(fill="both", expand=True)

child_env = dict(os.environ)
child_env["SDL_WINDOWID"] = str(frame.winfo_id())
child_env["SDL_VIDEODRIVER"] = "windib"
p = subprocess.Popen(["cmd.exe"], env=child_env)

root.mainloop()

但是,正如我所说,它不起作用。

【问题讨论】:

  • 这个问题已经问了好几次了。
  • 目前支持所有 Windows 控制台应用程序的唯一方法是隐藏控制台窗口并使用低级控制台 API 不断轮询输入缓冲区和活动屏幕缓冲区以进行更改。这就是替代控制台(如 ConEmu)的实现方式。
  • 对于 Windows 10,微软计划在秋季发布新的pseudoconsole feature。在 Python 方面,子进程模块(已在 3.7 中添加)中对 lpAttributeList 的支持需要扩展以支持 PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE。也许CreatePseudoConsole 和创建无缓冲管道FD 可以包装为pty.openpc(size, flags) -> (fdin, fdout, hpc)

标签: windows python-3.x tkinter command-line subprocess


【解决方案1】:
from tkinter import Tk, Text
import subprocess


def execute(code):
    command = cmd.get('1.0', 'end').split('\n')[-2]
    if command == 'exit':
        exit()
    cmd.insert('end', f'\n{subprocess.getoutput(command)}')


main = Tk()

cmd = Text(main)
cmd.pack()

cmd.bind('<Return>', execute)

main.mainloop()

【讨论】:

  • 您应该给出某种解释,您的代码如何解决问题并回答问题。这样一来,您的回答质量就会大大提高。
【解决方案2】:

这不使用 Windows 附带的程序中的“命令提示符”,但 ConEmu 有一个 -insidewnd 参数,旨在允许它嵌入到第三方应用程序中。

import sys,pathlib,subprocess
import tkinter as tk
import tkinter.ttk as ttk

# assuming a common location for the portable conemu installation:
conemu_exe = pathlib.Path.home()/"Documents"/"ConEmu"/"ConEmu64.exe"

class app(tk.Tk):
    def __init__(self):
        super().__init__()
        self.console_frame = ttk.Frame(self,height=480,width=640)
        self.console_frame.pack(fill="both",expand=True)
        hwnd = hex(self.console_frame.winfo_id())
        p = subprocess.Popen(
            [str(conemu_exe), "-insidewnd", hwnd],
            stdin=subprocess.PIPE,
            stdout=subprocess.PIPE)

app().mainloop()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-04
    • 1970-01-01
    • 2012-03-15
    • 1970-01-01
    • 2022-06-20
    • 2011-07-08
    • 2012-12-08
    • 1970-01-01
    相关资源
    最近更新 更多