簡體   English   中英

我的 exec 程序不工作

[英]My exec program isn't working

我正在嘗試制作一個程序,您可以在其中輸入一個代碼,該程序將執行該代碼。

當您按 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)

問題是,當我按下按鈕時,它只執行第一個條目。

有人可以告訴我我的代碼有什么問題嗎?

您處理“多行”條目的方式不起作用。 Enter 后,您將創建一個新的Entry小部件並立即將其內容附加到self.code 但是,此時內容是'' ,並且您也沒有保留對該新Entry的引用,因此在用戶有機會輸入一些文本之后,以后無法獲取內容。

可以將不同的Entry實例存儲在一個列表中,但我建議您只使用一個多行Text小部件:

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!")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM