Home > OS >  Python tkinter: NameError: name 'tk' is not defined
Python tkinter: NameError: name 'tk' is not defined

Time:09-23

from tkinter import*


root = tk.Tk()

canvas = tk.Canvas(root, width=600, height=500)
canvas.pack()


root.mainloop()

Why does this error come up? I have installed tkinter, so I dont know why it's saying this.

CodePudding user response:

tkinter is the package name. If you do a from tkinter import * you do not need any prefixes.

The tk. prefix is used when you import tkinter with

import tkinter as tk

Which is preferred over doing a star import, as it preserves the namespaces: there are hundreds of names in the tkinter package that upon doing from tkinter import * will be brought to the global namespace, making it hard to tell what is a variable you created, what is a Python built-in name, and what is part of the tkinter package. By doing import tkinter as tk, you can use and read everything tkinter prefixing it with tk. which is both easy to read and to type.

CodePudding user response:

you have 2 options

  1. `

    import tkinter as tk from tkinter import*

    root = tk.Tk()

    canvas = tk.Canvas(root, width=600, height=500) canvas.pack()

    root.mainloop()

    `

or

from tkinter import*


root = Tk()

canvas = Canvas(root, width=600, height=500)
canvas.pack()


root.mainloop()

you have to define tk first or you have to use tkinter instead of tk

CodePudding user response:

I think may be have a file with name tkinter.py in your current source code folder

  • Related