使用类

时间:2015-06-18 16:59:54

标签: python text tkinter

我想知道如何在按下“提交”按钮时保存用户在Text窗口小部件中输入的文本。目前,我有submitbutton函数,但点击“提交”时会出现错误。

另一方面,我希望右上角Label窗口小部件在文件打开并显示在左侧时更改其文本。

我到目前为止的代码是:

'''
Created on 17 Jun 2015

@author: lb89
'''
from Tkinter import *
import tkFileDialog 

from ScrolledText import *

#import zdra

specification = ""
inp = None

def combine_funcs(*funcs):
    def combined_func(*args, **kwargs):
        for f in funcs:
            f(*args, **kwargs)
        return combined_func

class Example(Frame):

    def __init__(self, master):
        Frame.__init__(self, master)   

        self.master = master        
        self.initUI()


    def initUI(self):
        global specification
        topMessage = StringVar()
        bottomMessage = StringVar()

        self.master.title("ZDRa Interface")
        self.pack(fill=BOTH, expand=1, side=LEFT)

        m1 = PanedWindow(self.master, width = 900)
        m1.pack(fill=BOTH, expand=1)

        scrollbar = Scrollbar(self)
        scrollbar.pack( side = RIGHT, fill=Y )

        menubar = Menu(self.master)
        self.master.config(menu=menubar)

        fileMenu = Menu(menubar)
        fileMenu.add_command(label="Open", command=self.onOpen)
        menubar.add_cascade(label="File", menu=fileMenu)

        self.txt = Text(self, yscrollcommand = scrollbar.set)
        self.txt.pack(fill=BOTH, expand=1)

        m2 = PanedWindow(m1, orient=VERTICAL)
        m1.add(m2)

        top = Label(m2, textvariable=topMessage, background = "white", height = 40, width = 70)
        m2.add(top)
        top.pack()

        bottom = ScrolledText(m2, wrap=WORD)
        m2.add(bottom)
        bottom.pack()

        scrollbar.config(command = self.txt.yview)

        self.txt.insert(END, "Please choose a specification by clicking on file then open")

        b = Button(m2, text = "Submit", command = self.submitbutton)
        b.pack(side = BOTTOM)

        topMessage.set("Please pick a specification from the top left")

    def submitbutton(self):
        print self.m1.bottom.get()


    def onOpen(self):
        global specification
        ftypes = [('Tex files', '*.tex'), ('All files', '*')]
        dlg = tkFileDialog.Open(self, filetypes = ftypes)
        fl = dlg.show()

        if fl != '':
            self.txt.delete(1.0, END)
            text = self.readFile(fl)
            self.txt.insert(END, text)
            for eachline in text:
                specification += eachline


    def readFile(self, filename):
        f = open(filename, "r")
        text = f.read()
        return text

def docheck():
    global specification
    print specification

def main():
    root = Tk()
    ex = Example(root)
    root.geometry("300x250+300+300")
    root.mainloop()

if __name__ == '__main__':
    main()

1 个答案:

答案 0 :(得分:2)

您需要保存对文本小部件的引用,并将参数传递给get方法,以告诉它要获取的数据范围:

self.bottom = ScrolledText(m2, wrap=WORD)
...
print self.bottom.get("1.0", "end-1c")