I am making a code editor. But when I type in my code editor the following code, it is getting a NameError.
import tkinter as tk
class App(tk.Tk):
def __init__(self):
super().__init__()
self.label = tk.Label(self, text="iets") # here, tk isn't recognized
self.label.pack()
app = App()
app.mainloop()
All the code of the input tkinter text widget is executed by a exec statement. The whole NameError is:
Traceback (most recent call last): File "C:\Users\Gebruiker\PycharmProjects\mylanguage\execute.py", line 24, in do exec(self.input) File "< string>", line 9, in File "< string>", line 6, in __ init__ NameError: name 'tk' is not defined
Why do i get this error? in the code I typed in I do have import tkinter as tk
!
The hierarchy of my project is the following: I've 8 files: main.py, execute.py, output.py et cetera
execute.py:
...
def do(self):
sys.stdout.write = output
try:
set_last("")
exec(self.input) #line 24
except Exception:
set_last("text.config(foreground='red')")
error = traceback.format_exc()
output(error)
...
when i add print(repr(self.input))
on top of do()
it outputs:
import tkinter as tk
class App(tk.Tk):
def __init__(self):
super().__init__()
self.label = tk.Label(self, text="iets")
self.label.pack()
app = App()
app.mainloop()
See the whole project on github: https://github.com/keizertje/myl
thanks in advance!
sorry for the consternation, the reason of my problem was totally other than i expected! the problem was that when i put self.input
in exec()
the program starts with all global variables. how to fix? as acw1668 said: simply use exec(self.input, {})
and it worked! this empty dict means that at the start of executing there are no global variables.
so do()
becomes:
def do(self):
sys.stdout.write = output
try:
set_last("")
exec(self.input, {}) # here it's fixed!
except Exception:
set_last("text.config(foreground='red')")
error = traceback.format_exc()
output(error)