使用字体模块的 Tkinter 代码无法从命令行运行? [英] Tkinter code using font module can't run from command line?

查看:24
本文介绍了使用字体模块的 Tkinter 代码无法从命令行运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有使用 tkinter 的代码,我可以从 IDLE 运行它,但是当它从命令行运行时会抛出异常 AttributeError: 'module' object has no attribute 'font'.其他 tkinter 程序工作正常,但使用 tkinter 包的 font.py 的任何程序都会给我这个错误.

I have code using tkinter which I can run from IDLE just fine, but which throws the exception AttributeError: 'module' object has no attribute 'font' when it is run from the command line. Other tkinter programs work fine, but anything using the tkinter package's font.py gives me this error.

我检查了我的 python 文件,c:/Python34/Lib/tkinter/font.py 就在那里.我不知道为什么,从命令行,它认为字体是一个属性,而不是 tkinter 包的模块.

I've checked my python files and c:/Python34/Lib/tkinter/font.py is there. I am not sure why, from the command line, it thinks font is an attribute and not a module of the tkinter package.

示例代码:

import tkinter as tk
from tkinter import ttk

root = tk.Tk()

test_font = tk.font.Font(size=12,weight='bold')

root.mainloop()

推荐答案

此处相同:

 Type "help", "copyright", "credits" or "license" for more information.
 >>> import tkinter as tk
 >>> tk.font
 AttributeError: 'module' object has no attribute 'font'

答案很简单:Python 不会自动导入所有模块层次结构,仅仅因为您导入了顶级层次结构.那些这样做的人(例如 os,这将使 os.path 可用)必须明确地为此编写代码.

The answer is simple: Python doesn't automagically import all module hierarchies, just because you import the top-level one. Those who do (e.g. os, which will make os.path available) have to explicitly write code for that.

然而,由于 IDLE 使用 tkinter 本身,它已经导入了 tkinter.font,因此您认为没有导入就可以逃脱.你不能.只需添加import tkinter.font,它就可以工作了.

However, as IDLE uses tkinter itself, it has already imported tkinter.font, thus you think you can get away without that import. You can't. Just add import tkinter.font, and it works.

这篇关于使用字体模块的 Tkinter 代码无法从命令行运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆