简体   繁体   中英

tkinter in Python3 (anaconda), “AttributeError: module 'tkinter' has no attribute 'Tk'”

I am trying to run this really short script:

print("import") 
import tkinter as tk 
print("program") 
tk.Tk()

However, I get this error:

Traceback (most recent call last):
import
  File "C:/Users/chris/PycharmProjects/untitled/tkinter.py", line 2, in <module>
import
    import tkinter as tk
program
  File "C:\Users\chris\PycharmProjects\untitled\tkinter.py", line 4, in <module>
    tk.Tk()
AttributeError: module 'tkinter' has no attribute 'Tk'

If I run the same commands directly in the python interpreter, it works fine:

In[5]: print("import")
import tkinter as tk
print("program")
tk.Tk()
import
program
Out[5]: <tkinter.Tk object .>

Further inspection of this code shows that when I run the code, it run itself twice, this is only the case if I am importing tkinter thought, it runs as expected otherwise.

I dont really know why this is happening. I tried reinstalling Anaconda (Python 3.5), but it didn't help.

You have named the python file you are trying to execute tkinter.py
which, as a result, overshadows the tkinter library. The python import system first looks in the current working directory for a module and then in the standard paths for built-ins.

Change the name of the file to something different, like tkinterscript.py and the import will be successful.

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