2013-07-24 67 views
0

我一直在試圖創建自己的基本Python IDE。我創建了一個界面,其中包含一個輸入文本框,它允許我輸入語法和pmw.ScrolledText,它顯示Python解釋器的輸出結果。Tkinter輸入和輸出在一個小工具

我真正希望做的是將這兩個小部件組合成一個可以處理輸入和輸出的小部件。我還沒有找到任何這樣的小部件,但我相當肯定有可能以某種方式做到這一點,因爲Idle是用Tk編寫的,基本上是我在我的應用程序中尋找的東西。查看空閒的源代碼並沒有真正向我展示一個簡潔的方法來做到這一點。

基本上我正在尋找一個像pmw.ScrolledText這樣的輸入並可以顯示輸出。

我只是想知道這是否可能與Tk和可能的路線,可以採取任何想法,使其工作。

謝謝。

+0

IDLE使用的基本上是[Text Widget](http://effbot.org/tkinterbook/text.htm),一個用於編輯器,另一個用於控制檯。 –

回答

2

這絕對有可能。文本小部件就是您想要使用的,但您必須執行一些編碼來處理顯示提示,然後在用戶點擊返回鍵時執行操作。

我認爲最簡單的做法是在插入提示符後立即設置一個標記,然後當您檢測到返回鍵時,將該標記的所有內容作爲要運行的命令抓取到文件末尾。

下面是說明該技術的簡要示例。這並不完美(例如,您可以刪除提示),但它顯示了一般想法。

import Tkinter as tk 

class Application(tk.Frame): 
    def __init__(self, master): 
     tk.Frame.__init__(self, master) 
     self.text = tk.Text(self, wrap="word", height=20) 
     self.vsb = tk.Scrollbar(self, orient="vertical", command=self.text.yview) 
     self.text.configure(yscrollcommand=self.vsb.set) 
     self.vsb.pack(side="right", fill="y") 
     self.text.pack(side="left", fill="both", expand=True) 

     self.text.bind("<Return>", self.process_input) 
     self.prompt = ">>> " 

     self.insert_prompt() 

    def insert_prompt(self): 
     # make sure the last line ends with a newline; remember that 
     # tkinter guarantees a trailing newline, so we get the 
     # character before this trailing newline ('end-1c' gets the 
     # trailing newline, 'end-2c' gets the char before that) 
     c = self.text.get("end-2c") 
     if c != "\n": 
      self.text.insert("end", "\n") 
     self.text.insert("end", self.prompt, ("prompt",)) 

     # this mark lets us find the end of the prompt, and thus 
     # the beggining of the user input 
     self.text.mark_set("end-of-prompt", "end-1c") 
     self.text.mark_gravity("end-of-prompt", "left") 

    def process_input(self, event=None): 
     # if there is an event, it happened before the class binding, 
     # thus before the newline actually got inserted; we'll 
     # do that here, then skip the class binding. 
     self.text.insert("end", "\n") 
     command = self.text.get("end-of-prompt", "end-1c") 
     self.text.insert("end", "output of the command '%s'...!" % command) 
     self.text.see("end") 
     self.insert_prompt() 

     # this prevents the class binding from firing, since we 
     # inserted the newline in this method 
     return "break" 

root = tk.Tk() 
root.wm_geometry("400x100") 
app = Application(root).pack(side="top", fill="both", expand=True) 

root.mainloop() 
+0

感謝您的回覆。我可以看到文本小部件如何用於輸入,但是如何顯示輸出?我是否需要在文本小部件上方立即顯示輸出的小部件? (pmw.ScrolledText似乎只支持降序) – Matt

+0

@Matt:如何顯示輸出?你只需將它插入到小部件中(例如:'the_text_widget.insert(「end」,「output」)') –

+0

那真是一個愚蠢的問題。我不知道我可以用文本小部件來做到這一點。不得不寫一個小程序來試用。謝謝您的幫助! – Matt