请用使用tkinter库,用python代码编写一个程序,学生在窗口中输入代码,程序检查学生编写的代码是否有语法错误,以及是否实现了正确的功能,要求实现的功能是输出“hello world",另外,学生输入代码的时个,最好能有代码补全提示
时间: 2024-03-21 21:42:30 浏览: 17
好的,以下是使用 Tkinter 库编写的程序,可以实现学生在窗口中输入代码,程序检查学生编写的代码是否有语法错误,以及是否实现了正确的功能,要求实现的功能是输出“hello world”,并提供代码补全提示。
```python
import tkinter as tk
import code
import jedi
class CodeChecker:
def __init__(self, master):
self.master = master
master.title("代码检查器")
# 创建输入框和按钮
self.text = tk.Text(master, height=20, width=50)
self.text.pack(side=tk.LEFT)
self.check_button = tk.Button(master, text="检查代码", command=self.check_code)
self.check_button.pack(side=tk.LEFT)
# 创建消息框
self.message = tk.Text(master, height=5, width=50)
self.message.pack(side=tk.BOTTOM)
def check_code(self):
# 获取学生编写的代码
student_code = self.text.get("1.0", tk.END)
# 检查学生编写的代码是否有语法错误
try:
compile(student_code, '<string>', 'exec')
except SyntaxError as e:
self.message.insert(tk.END, "学生编写的代码存在语法错误:{}\n".format(e))
else:
self.message.insert(tk.END, "学生编写的代码没有语法错误。\n")
# 检查学生编写的代码是否输出了“hello world”
namespace = {}
try:
exec(student_code, namespace)
except Exception as e:
self.message.insert(tk.END, "学生编写的代码存在错误:{}\n".format(e))
else:
if 'hello world' in namespace.values():
self.message.insert(tk.END, "学生编写的代码输出了“hello world”。\n")
else:
self.message.insert(tk.END, "学生编写的代码没有输出“hello world”。\n")
# 为学生提供代码补全提示
completer = jedi.Completer(student_code, {})
completions = completer.complete()
self.message.insert(tk.END, "代码补全提示:{}\n".format(completions))
root = tk.Tk()
code_checker = CodeChecker(root)
root.mainloop()
```
这个程序会创建一个窗口,学生可以在窗口中输入代码。点击“检查代码”按钮,程序会检查学生编写的代码是否有语法错误,并检查是否实现了正确的功能(输出“hello world”)。同时,程序还会为学生提供代码补全提示。程序的检查结果和补全提示会显示在窗口的消息框中。