【问题标题】:Python tkinter button showing script to scrolledtext boxPython tkinter 按钮显示脚本到滚动文本框
【发布时间】:2021-09-23 00:23:15
【问题描述】:

当我按下开始按钮时,它会运行另一个脚本,但只在另一个终端中显示它,而不是在我拥有的 GUI 滚动文本框中。我的问题有简单的解决方法吗?在任何地方都找不到答案。

from tkinter import *
from tkinter import ttk
from tkinter import filedialog
import sys
import os
import tkinter.scrolledtext as tkst

root = Tk()
root.title("WLP")
root.geometry("950x450")
root.iconbitmap("Vo1d.ico")
root.configure(bg='#0c0c0c')

def clickstart():
  os.system('python WLP.py')

Button1 = Button(root, text="START", bg="#0c0c0c", fg="#C0C0C0", command=clickstart)  #)
Textbox = tkst.ScrolledText(root, width=75, height=10, bg="#0c0c0c", fg="#C0C0C0")
Button1.grid(row=10, column=5, pady=15)
Textbox.grid(row=17, column=5)

root.mainloop()

【问题讨论】:

  • 你想做什么?
  • 当我按下 button1 时,我试图让“wlp.py”的结果显示在我的滚动文本(文本框)中。我现在得到的只是当我按下按钮 1 时在我的 GUI 后面的终端中显示的“wlp.py”的结果。 @PCM
  • os.system() 不允许您访问正在运行的命令的输出。您可能需要来自 subprocess 模块的东西 - .run()
  • @DwughtFromTheOffice,这在运行 .py 文件时稍作修正。但是,在编译脚本并按下 .exe 文件中的按钮后,它根本不会在滚动文本(文本框)中显示结果。您或任何人能想到的任何想法或解决方法?在 .exe 文件后面的终端中,它声明: subprocess.CalledProcessError: Command '['python', 'wlp1.py']' returned non-zero exit status 2.
  • @Vo1d 是因为check=Truesubprocess.run(...) 中使用了答案。如果WPL.py 的返回码不为零,则会引发异常。删除check=True

标签: python tkinter button


【解决方案1】:

这远不是一个好方法,但这应该可以工作(在导入子流程之后)

def clickstart():
    output = subprocess.run(['python', 'WPL.py'], stdout=subprocess.PIPE, check=True)
    output = str(output.stdout, encoding='utf-8')
    Textbox.insert(1.0, output)

【讨论】:

  • insert 的索引应该是字符串,而不是浮点数。浮点数将在这种特定情况下工作,但该函数被定义为采用字符串。
猜你喜欢
  • 2022-10-24
  • 1970-01-01
  • 1970-01-01
  • 2019-08-12
  • 2021-12-20
  • 1970-01-01
  • 1970-01-01
  • 2022-01-23
  • 1970-01-01
相关资源
最近更新 更多