简体   繁体   English

Python3(anaconda)中的tkinter,“ AttributeError:模块'tkinter'没有属性'Tk'”

[英]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: 如果我直接在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),但没有帮助。

You have named the python file you are trying to execute tkinter.py 您已将要执行的Python文件命名为tkinter.py
which, as a result, overshadows the tkinter library. 结果,这使tkinter库黯然失色。 The python import system first looks in the current working directory for a module and then in the standard paths for built-ins. python import系统首先在当前工作目录中查找模块,然后在内置文件的标准路径中查找。

Change the name of the file to something different, like tkinterscript.py and the import will be successful. 将文件名更改为其他名称,例如tkinterscript.py ,导入将成功。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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