【问题标题】:Getting "ModuleNotFoundError" trying to import Tkinter Canvas?尝试导入 Tkinter Canvas 时遇到“ModuleNotFoundError”?
【发布时间】:2021-08-12 17:56:00
【问题描述】:

我正在尝试做与 Marc Leese 在这里尝试做的事情相同的事情,但似乎没有得到明确的答案(至少没有一个对我有用):trying to convert this file to python 3 and getting the error module not found

也就是说,在 Python 3+ 环境中使用所找到的 solitaire.py 示例代码,例如这里:https://android.googlesource.com/toolchain/python/+/0d4194853e08d3244931523470331c00dfb94863/Python-2.7.3/Demo/tkinter/guido/solitaire.py

具体来说,我正在通过 Spyder 3.3.6 运行 Python 3.7.9。

当我尝试运行上面的代码时,我首先得到一个错误,即找不到 Tkinter。但是,当我将 Tkinter 更正为 tkinter 时,我仍然收到一条错误消息:

ModuleNotFoundError: No module named 'Canvas'

无论我使用from tkinter import * 还是from tkinter import Canvas,我都会遇到同样的错误。

有问题的整个代码块是:

# Imports
import math
import random
from tkinter import *
from Canvas import Rectangle, CanvasText, Group, Window
# Fix a bug in Canvas.Group as distributed in Python 1.4.  The
# distributed bind() method is broken.  Rather than asking you to fix
# the source, we fix it here by deriving a subclass:
class Group(Group):
    def bind(self, sequence=None, command=None):
        return self.canvas.tag_bind(self.id, sequence, command)

我之前注意到使用import * 的示例代码似乎不像示例中那样工作,但在我一直设法找到解决方法之前。

如果有人能解释这里发生了什么/如何解决它,我将非常感激!

【问题讨论】:

  • Canvas 没有模块,一个模块,而不是一个类,你通常是从模块中导入的,在你的代码中,你在哪里看到你导入的模块名为 Canvas?另外:我强烈建议不要在导入某些东西时使用通配符(*),您应该导入您需要的东西,例如from module import Class1, func_1, var_2 等等或导入整个模块:import module 然后你也可以使用别名:import module as md 或类似的东西,关键是不要导入所有东西,除非你真的知道你在做什么;名称冲突是问题所在。
  • 这似乎与 tkinter 无关。 Canvas 不是 tkinter 提供的模块,RectangleCanvasTextGroupWindow 也不是。您能否显示有关您尝试导入的模块的文档链接?
  • 嗨,马蒂斯。正如我在帖子中所写,这不是我的代码,我正在尝试使用 python 包中包含的演示示例程序之一。你可以在我的第二个链接中看到整个程序,如果你用谷歌搜索“tkinter guido solitaire”,也可以在其他地方看到。
  • @BryanOakley from tkinter import Canvas 在 3.9 中适用于我,from Tkinter import Canvas 在 2.7 中适用。
  • 嗨,布莱恩,感谢您的回答。我链接的第一个问题中的一个答案建议从 tkinter 导入 Canvas。我从那里得到了暗示。但也许他们弄错了,我很困惑,应该尝试安装一个与 tkinter 无关的 Canvas 模块?

标签: python python-3.x tkinter canvas


【解决方案1】:

您复制了一些非常古老的代码,这些代码显然依赖于名为“Canvas”的模块(例如,名为 Canvas.py 的文件)。这个模块不是 tkinter 的一部分。您需要找到原始的Canvas.py 文件

【讨论】:

  • 谢谢!我还没有找到原始模块,但我认为你的回答至少解释了我的问题和一年多前的另一个问题。对于其他有同样问题的人:我个人最终遵循了@Matiis 的建议,并找到了 Andereoo 的一个更新的 tkinter solitaire 示例程序来代替使用。
猜你喜欢
  • 1970-01-01
  • 2020-03-21
  • 2022-10-16
  • 1970-01-01
  • 1970-01-01
  • 2018-09-02
  • 1970-01-01
  • 2019-07-03
  • 2017-07-29
相关资源
最近更新 更多