2016-04-02 12 views
2

私はプログラムを作成しようとしています。そのプログラムにはエントリにコードを入力することができ、プログラムはそのコードを実行します。私のexecプログラムが動作していません

Enterキーを押すと、プログラムは前のエントリの下に別のエントリを作成します。

"プログラムの実行"ボタンを押すと、書き込んだコードがすべて実行されます。

from tkinter import * 

class Application(Frame): 
    def __init__(self, master): 
    Frame.__init__(self, master) 
    self.grid() 

    self.entry1=Entry(self) 
    self.entry1.grid(row=0, column=0, sticky=W) 

    self.bttn1=Button(self, text="Execute code", command=self.execute_code) 
    self.bttn1.grid(row=1, column=9, sticky=W) 

    self.rows=0 

    self.entry1.bind("<Return>", self.down) 



    def execute_code(self): 
     self.code=self.entry1.get() 

     try: 
     exec(self.code) 
     except: 
     print("There is something wrong with this code!") 

def down(self,event): 
     self.rows+=1 

     entry=Entry(self) 
     entry.grid(row=self.rows, column=0, sticky=W) 
     self.code=self.code+"\n"+entry.get() 
     entry.bind("<Return>", self.down) 


root=Tk() 
root.title("Executing code") 
root.geometry("500x500") 
app=Application(root) 

問題は、ボタンを押すと、最初のエントリだけが実行されることです。

誰かが自分のコードで何が間違っているか教えてもらえますか?

+0

を単一の複数行のテキストフィールドを使用する方法はありますか? –

+0

それはprint(3)のために実行します、何をしようとしていますか? –

+0

Enterキーを押すとクラッシュします。 –

答えて

1

「複数行」のエントリを扱う方法は機能しません。 を入力してと入力し、新しいEntryウィジェットを作成し、すぐにコンテンツをself.codeに追加します。しかし、その時点でコンテンツは''であり、その新しいEntryへの参照を保持しないため、ユーザーがテキストを入力した後でコンテンツを取得する方法がありません。

あなたはリストに異なるEntryインスタンスを格納することができ、その代わりに、私はあなただけで単一のマルチラインTextウィジェット使用することをお勧め:代わりに、より多くの1行入力フィールドを追加するので

class Application(Frame): 
    def __init__(self, master): 
     Frame.__init__(self, master) 
     self.grid() 

     self.entry1 = Text(self) 
     self.entry1.grid(row=0, column=0, sticky=W) 

     self.bttn1 = Button(self, text="Execute code", command=self.execute_code) 
     self.bttn1.grid(row=1, column=0, sticky=W) 

    def execute_code(self): 
     code = self.entry1.get("0.0", "end") 
     try: 
      exec(code) 
     except: 
      print("There is something wrong with this code!") 
関連する問題