简体   繁体   中英

NameError: name 'tkinter' is not defined

so i tried to work with tkinter and i got this error on a very simple code could you help me?

the code:

from tkinter import *
window = Tk()
l1 = tkinter.Label(window, text = "exmple text" , font = ("Arial" , 14))
l1.grid(row =0 ,column = 0 , sticky = E)
window.mainloop()

the error i get:

NameError: name 'tkinter' is not defined

i dont know what am i missing because i saw pepole online that simple codes like this work for them

I see a little mistake made when you try to call Label from tkinter...

First of all, i'm gonna proceed to put the correct code and then i'll explain some details about it:

from tkinter import *
window = Tk()
l1 = Label(window, text = "exmple text" , font = ("Arial" , 14))
l1.grid(row =0 ,column = 0 , sticky = E)
window.mainloop()

Your mistake was that you tried to use

l1 = tkinter.Label(window, text = "exmple text" , font = ("Arial" , 14))

doing from tkinter import * you load all of tkinter's namespace into your module's namespace, so you can not call tkinter and the module again... instead, you just call the module.That's why your error was telling you have not defined tkinter.

Anyways, doing this type of import it's bad, cause you can make some silly mistakes and end up with unpleasant namespace collisions.

The right syntax and format would be an import tkinter and then call tkinter's function, just to prevent namespace collisions and loosing time by looking were did you fail.

You should checkout this question made some time ago to get more details about what i'm talking! Tkinter importing without *?

EDIT: Use this code, should work and you won't have to worry about namespace collision:)

import tkinter
window = tkinter.Tk()
l1 = tkinter.Label(window, text = "example text" , font = ("Arial" , 14))
l1.grid(row =0 ,column = 0 , sticky = tkinter.E)
window.mainloop()

Just import tkinter like this:

import tkinter

window = tkinter.Tk()
l1 = tkinter.Label(window, text = "exmple text" , font = ("Arial" , 14))
l1.grid(row =0 ,column = 0 , sticky = tkinter.E)
window.mainloop()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM