簡體   English   中英

獲取命令窗口輸出以使用tkinter在窗口小部件中顯示

[英]Get command window output to display in widget with tkinter

快速項目摘要 :使用Tkinter創建一個python小部件,該小部件顯示來自多個json和txt文件的數據。 需要在Windows中工作。 我在哪里 :json文件的一切都很好。 但我遇到了txt文件的問題。 我可以使用以下代碼從必要的文件中解析我需要的信息:

from Tkinter import *
import re


results = open("sample_results.txt", "r")

for line in results:
    if re.match("(.*)test(.*)", line):
        print line
    if re.match("(.*)number(.*)", line):
        print line
    if re.match("(.*)status(.*)", line):
        print line
    if re.match("(.*)length(.*)", line):
        print line

問題 :它顯示命令shell中的所有數據,而不是單獨的小部件。

我想簡單地將所有這些信息從命令shell移動到文本框小部件(或tkmessage小部件,但我覺得文本框更合適)。 一個很長的谷歌搜索過程給了我很多不起作用的代碼 - 任何提示? 謝謝!

注意:這不是所有代碼 - 只是我需要幫助修復的部分

這就是我想你想要的。 您希望應用程序打開文件並解析它們。 對於每個已解析的行,您希望它將文本(或附加文本)插入到文本控件中。 我會為每種文件類型創建一個方法來進行解析。 然后我會遍歷每個文件並根據需要調用解析器。 完成解析后,您可以調用

self.textbox.insert(tkinter.END, parsed_text)

另一種方法是將stdout重定向到文本控件,然后打印解析的行。 我發現后一種方法更靈活,特別是當我想用子進程調用一個單獨的程序並逐位讀取它的輸出時。 以下是使用Tkinter進行此操作的一種方法:

import ScrolledText
import sys
import tkFileDialog
import Tkinter


########################################################################
class RedirectText(object):
    """"""

    #----------------------------------------------------------------------
    def __init__(self, text_ctrl):
        """Constructor"""
        self.output = text_ctrl

    #----------------------------------------------------------------------
    def write(self, string):
        """"""
        self.output.insert(Tkinter.END, string)


########################################################################
class MyApp(object):
    """"""

    #----------------------------------------------------------------------
    def __init__(self, parent):
        """Constructor"""
        self.root = parent
        self.root.title("Redirect")
        self.frame = Tkinter.Frame(parent)
        self.frame.pack()

        self.text = ScrolledText.ScrolledText(self.frame)
        self.text.pack()

        # redirect stdout
        redir = RedirectText(self.text)
        sys.stdout = redir

        btn = Tkinter.Button(self.frame, text="Open file", command=self.open_file)
        btn.pack()

    #----------------------------------------------------------------------
    def open_file(self):
        """
        Open a file, read it line-by-line and print out each line to
        the text control widget
        """
        options = {}
        options['defaultextension'] = '.txt'
        options['filetypes'] = [('all files', '.*'), ('text files', '.txt')]
        options['initialdir'] = '/home'
        options['parent'] = self.root
        options['title'] = "Open a file"

        with tkFileDialog.askopenfile(mode='r', **options) as f_handle:
            for line in f_handle:
                print line

#----------------------------------------------------------------------
if __name__ == "__main__":
    root = Tkinter.Tk()
    root.geometry("800x600")
    app = MyApp(root)
    root.mainloop()

一種方法是使用簡單的tkinter標簽:

# somewhere in your main class, I suppose:
self.log_txt = tkinter.StringVar()                                                                                                                                                                                                                                    
self.log_label = tkinter.Label(self.inputframe, textvariable=self.log_txt, justify=tkinter.LEFT)                                                                                                                                                                      
self.log_label.pack(anchor="w")   

然后,一個非常簡單的方法將文本放入該標簽:

def log(self, s):                                                                                                                                                                                                                                                         
    txt = self.log_txt.get() + "\n" + s                                                                                                                                                                                                                                   
    self.log_txt.set(txt)  

或者,您可以使用tkinter.Text小部件。 在這種情況下,您可以使用insert方法插入文本:

self.textbox = tkinter.Text(parent)
self.textbox.insert(tkinter.END, "some text to insert")

我喜歡的一個資源是http://effbot.org/tkinterbook/text.htm 不幸的是,很難從那個文本轉到使用Python代碼:(

這是一個小示例程序,帶有一個丑陋的小tkinter GUI,可以將文本添加到文本框中:

#!/usr/bin/env python

try:
    import tkinter
except ImportError:
    import Tkinter as tkinter
import _tkinter
import platform

class TextBoxDemo(tkinter.Tk):
    def __init__(self, parent):
        tkinter.Tk.__init__(self, parent)
        self.parent = parent
        self.wm_title("TextBoxDemo")
        self.textbox = tkinter.Text(self)
        self.textbox.pack()

        self.txt_var = tkinter.StringVar()
        self.entry = tkinter.Entry(self, textvariable=self.txt_var)
        self.entry.pack(anchor="w")

        self.button = tkinter.Button(self, text="Add", command=self.add)
        self.button.pack(anchor="e")


    def add(self):
        self.textbox.insert(tkinter.END, self.txt_var.get())


if __name__ == '__main__':
    try:
        app = TextBoxDemo(None)
        app.mainloop()
    except _tkinter.TclError as e:
        if platform.system() == 'Windows':
            print(e)
            print("Seems tkinter will not run; try running this program outside a virtualenv.")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM