【问题标题】:tkinter not importable from terminal but works in Python 3 shell on Raspberry Pitkinter 无法从终端导入,但可以在 Raspberry Pi 上的 Python 3 shell 中使用
【发布时间】:2015-02-13 21:16:46
【问题描述】:

提前感谢您的帮助我已经卡了将近一个星期了!

我正在尝试在我的 Pi 上使用 tkinter,以下在 python 应用程序(shell)中运行时可以正常工作:

import tkinter
tk = tkinter.Tk()
window = tkinter.Tk()
tk.mainloop

但是当我输入命令时:

python /home/pi/myfiles/windowtest.py

在终端,我得到了

ImportError: No module named tkinter

到目前为止,我已经尝试过 sudo apt-get install tkinter,与更新、dev、tk、-f、python-tkinter 和任何其他我能想到的相同。 事实上sudo apt-get install tkinter 是无法定位到包的,和python-tkinter 一样。

sudo apt-get install python-tk 告诉我已经安装了最新版本。

我用的是最新的 NOOBS,大约 10 天前安装的。

背景 - 我想运行一些由 crontab 启动的使用 mplayer 的 python 脚本,目前所有的 mplay 简介都会在终端模式下将我的菜单从屏幕上推开,我看不到它。我希望 tkinter 会打开一个窗口,我可以将菜单放入其中并查看它。

【问题讨论】:

  • 你运行的是 Python 2 还是 Python 3?
  • Raspberry PI,Python 3,虽然我也安装了 Python 2,我可以尝试使用。

标签: python python-3.x tkinter terminal mplayer


【解决方案1】:

问题是模块在 Python 2 中命名为 Tkinter,在 Python 3 中命名为 tkinter。在 Debian、Raspbian、Ubuntu 等中,命令行上的 python 启动 Python 2.x(通常为 2.7现在)而需要 python3 来运行 Python 3.x 解释器。

由于这是一个新项目,我猜你应该只使用 Python 3(并且你已经为 Python 3 编写了代码),因此使用 python3 运行命令:

python3 /home/pi/myfiles/windowtest.py

% python
Python 2.7.6 (default, Mar 22 2014, 22:59:56) 
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import tkinter
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named tkinter
>>> import Tkinter
>>> 

对比

% python3
Python 3.4.0 (default, Apr 11 2014, 13:05:11) 
[GCC 4.8.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import tkinter
>>>

【讨论】:

  • 感谢您的回复,但我没有使用 PC。我想做的一切都在 PI 上。我在 PI 上使用 Python 3,请继续提供帮助!
  • 非常感谢,这是一个简单的答案,我一直在寻找并使用我太多的脑力思考。今晚我可以睡个好觉了。接下来我需要弄清楚如何让 crontab 运行它,这样我才能看到窗口。
  • 请注意,如果您使用的是 crontab,则需要显式设置 DISPLAY=:0 环境变量,以便它知道要在哪个显示器上运行...如果您认为我解决了您的问题,请勾选我的答案作为接受的答案。
  • 感谢 crontab 的另一天。你的解决方案效果很好,我已经测试过了。太感谢了 。 . .
【解决方案2】:

运行脚本:

python3 main.py

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-16
    • 2022-09-28
    • 2016-06-24
    • 2018-11-14
    • 2019-07-06
    • 2019-09-09
    • 1970-01-01
    • 2017-09-07
    相关资源
    最近更新 更多