在Python3 (anaconda)中的tkinter,“AttributeError: module‘tkinter’没有属性‘Tk’”。

时间:2022-08-09 12:19:09

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:

如果我在python解释器中直接运行相同的命令,它可以正常工作:

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.

对这段代码的进一步检查表明,当我运行代码时,它会运行两次,这只是如果我导入tkinter思想的情况,它会像预期的那样运行。

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

我不知道为什么会这样。我尝试重新安装Anaconda (Python 3.5),但是没有用。

1 个解决方案

#1


4  

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.

您已经命名了要执行tkinter的python文件。结果,它使tkinter库相形见绌。python导入系统首先查看模块的当前工作目录,然后在构建-ins的标准路径中查找。

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

将文件的名称更改为不同的,如tkinterscript。py和导入将会成功。

#1


4  

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.

您已经命名了要执行tkinter的python文件。结果,它使tkinter库相形见绌。python导入系统首先查看模块的当前工作目录,然后在构建-ins的标准路径中查找。

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

将文件的名称更改为不同的,如tkinterscript。py和导入将会成功。