【问题标题】:Circular import generating an AttributeError when importing tkinter循环导入在导入 tkinter 时生成 AttributeError
【发布时间】:2021-01-20 02:59:41
【问题描述】:

我有一个带有 python 3.9.1 的 Anaconda 环境,当我尝试导入 tkinter 时收到以下错误消息。

Traceback (most recent call last):
  File "/Users/isevilla/opt/miniconda3/envs/lab/lib/python3.9/site-packages/IPython/core/interactiveshell.py", line 3418, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-2-537f0be70a2b>", line 1, in <module>
    runfile('/Users/isevilla/Documents/Tkinter playground/tkinter.py', wdir='/Users/isevilla/Documents/Tkinter playground')
  File "/Applications/PyCharm CE.app/Contents/plugins/python-ce/helpers/pydev/_pydev_bundle/pydev_umd.py", line 197, in runfile
    pydev_imports.execfile(filename, global_vars, local_vars)  # execute the script
  File "/Applications/PyCharm CE.app/Contents/plugins/python-ce/helpers/pydev/_pydev_imps/_pydev_execfile.py", line 18, in execfile
    exec(compile(contents+"\n", file, 'exec'), glob, loc)
  File "/Users/isevilla/Documents/Tkinter playground/tkinter.py", line 1, in <module>
    import tkinter as tk
  File "/Applications/PyCharm CE.app/Contents/plugins/python-ce/helpers/pydev/_pydev_bundle/pydev_import_hook.py", line 21, in do_import
    module = self._system_import(name, *args, **kwargs)
  File "/Users/isevilla/Documents/Tkinter playground/tkinter.py", line 4, in <module>
    root = tk.Tk()
AttributeError: partially initialized module 'tkinter' has no attribute 'Tk' (most likely due to a circular import)

当我尝试运行以下简单代码时弹出错误:

import tkinter as tk


root = tk.Tk()

myLabel = tk.Label(root, text='Hello world')
myLabel.pack()

root.mainLoop()

有人知道为什么会发生这种情况,我该如何解决?

【问题讨论】:

  • 您将脚本命名为tkinter.py,将其重命名为其他名称。
  • 可能是stackoverflow.com/questions/20998275/…,不过既然是Python 3,那肯定是pydev/anaconda有问题了..
  • 嗨,是的,显然是我的文件名造成了冲突。当我改变它时它起作用了。感谢您的信息!

标签: python tkinter


【解决方案1】:

问题是您将文件命名为 Tkinter.py。当您进行导入时,python 会看到该文件并尝试导入它而不是 Tkinter 库。

重命名您的文件,并确保删除 Tkinter.pyc(如果存在)。

【讨论】:

  • 是的,你是对的。一旦我更改了名称,它就起作用了!
猜你喜欢
  • 1970-01-01
  • 2018-06-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-20
  • 1970-01-01
  • 2014-04-06
  • 2021-03-27
相关资源
最近更新 更多