Tkinter: Tk() not found

Asked

Viewed 258 times

0

When trying to call the function Tk(), it is not recognized by showing the following message: Nameerror: name 'Tk' is not defined

I’m trying to start the following code:

from tkinter import *

root = Tk()

Label(root, text="teste").pack()

root.mainloop

I have python 3.8.0 installed, using with Pycharm (I have already installed Tkinter in the package manager), I have already installed Tcl (I saw that could help). I have already modified Tkinter’s import script by varying between lowercase and uppercase the first letter. But no results yet. Any tips on how I can fix this situation? Thanks in advance for the attention of those who propose to contribute :)

  • I know it’s a very silly question that I’m going to ask, but surprisingly this happens many times. Have you checked if there is a tkinter.py in the same directory of your program ? If it exists, you will be importing this module that certainly does not contain the Tk().

  • I made an edit this time (which is waiting for approval), but when putting code, always select the part of the code and press Ctrl + k

  • is using linux? when I do a new distro installation, I also install Idle, it is guaranteed that Tkinter will come along, because Idle is made in Tk

  • Solved! The problem was that I had put the file name of Tkinter.py being that this name cannot be used in the file because it is a reserved word by the tool (that’s what I understood rsrs). I thank the friends who are willing to clarify the operation of the tool. I am a beginner and was very helpful to your collaboration. Vlw! : D

3 answers

1


Make sure you have not named your file for something like tkinter.py. It is a common mistake, but you cannot name a file whose name is the same as a module you are importing, there will be collision between the names of the module and its file.

  • It worked, it was really the name of the file, that for the sake of testing I put the name of the file of Tkinter.py I am beginner in this tool, so I did not imagine that it could interfere I appreciate the simplicity and clarity of the information. Vlw man! D

  • @Nathan-Santos if the answer helped you mark it as correct by clicking on

0

There’s a single error in your code, in last line.

You wrote

root.mainloop

When the right thing would be

root.mainloop()

Note that the mainloop comes with parentheses, so mainloop()

Your code then stays:

from tkinter import *

root = Tk()

Label(root, text="teste").pack()

root.mainloop

-1

Try it like this:

# importa o módulo tkinter como tk
import tkinter as tk

# cria a janela principal
root = tk.Tk()

# cria um label
lbl = tk.Label(root, text="teste")

# mostra o label
lbl.pack()

# loop da tela
root.mainloop()

Browser other questions tagged

You are not signed in. Login or sign up in order to post.