2015-06-18 36 views
1

我想知道如何在按下「提交」按鈕時保存用戶在Text小部件中輸入的文本。目前,我有功能submitbutton,但點擊「提交」時會出現錯誤。使用類時將用戶輸入保存到文本小部件Tkinter中

在另一個說明中,我想要右上角的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() 
+0

1.什麼是錯誤? 2.'initUI'中唯一沒有被拋棄的變量是'self.txt'。所有其他人都在本地功能範圍內。這意味着'submitbutton'不會知道'm1',並且'self.m1'從來沒有被分配過。 – TigerhawkT3

回答

2

您需要的參數保存到文本組件的引用,並傳遞給get方法,告訴它的數據是什麼範圍得到:

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

@lburski:把頭髮拉出來之前的第一步應該是閱讀一些文檔。這些信息在很多地方都有記錄。 –

相關問題