python - 将我的控制台输出重定向到我的 Tkinter 文本区域小部件

标签 python tkinter

我是 tkinter 的新手,我的代码可以运行,但我需要我的文本小部件仅显示 callback() 函数中的结果变量,不包括 'askopenfilename' 方法。

from Tkinter import *
    from tkFileDialog import *
    import os

    root = Tk()
    root.geometry('900x700')
    path = StringVar()

    #browse pdf files
    def callback():
    f = askopenfilename(title='Open Files',initialdir='C:\Users\shantini\Desktop\PDF',
                        filetypes=[('Files of type:','*.PDF'),('Files of type:','*.pdf')])
    path.set(f)
    result = os.popen('pdfid.py'+' '+f).read()
    return result

#labelframe(text pdf output)
label=LabelFrame(root, text="PDF Analysis Output")
label.pack(side=BOTTOM, anchor=W, fill=BOTH, expand=YES)
text = Text(label,bg='white')
text.pack(fill=BOTH, expand=YES)
text.insert(INSERT,callback())

root.mainloop()

最佳答案

如果禁用文本小部件,则会将其设为只读,因此无法向其添加文本。所以要添加文本,使其正常,或删除状态参数。我更改了您的回调以反射(reflect)评论:

def callback():
    f = askopenfilename(title='Open Files',initialdir='/tmp',
                        filetypes=[('Files of type:','*.PDF'),('Files of type:','*.pdf')])

    result = open(f).read() # I also changed this as I dont have `pdfid.py` to test the code
    text_area.insert(INSERT, result)
    print result

我稍微更改了输入文件和文件夹,因为我在 Linux 中工作并且不能使用 Windows 路径。希望这会有所帮助。

关于python - 将我的控制台输出重定向到我的 Tkinter 文本区域小部件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29295088/

相关文章:

python - 在mysql表中插入python变量时出错

python - 在 for 循环中创建多个 tkinter 小部件并将它们分配给变量

python - 为什么我的函数落后一键运行?

python - 如何使用 Tkinter 移动 Canvas 图像?

python - 将值打印到 Tkinter 标签

python - 在 Python 中打印类中对象的属性

python - 如何替换 Pandas 中的值?

python - PyUnicode_AsUTF8() 段错误

python - tkinter 中的标签宽度

javascript - Django CSRF token 丢失