我在 Windows 中使用 PyCharm,我已经通过 Anaconda 以及 tkinter 模块下载了 Python 3.5.5 和所有其他库。在此之前,我一直在使用它来解决任何问题。上次我安装了live Streamer 库。我认为这会导致问题。尝试资本和小:
from Tkinter import * , from tkinter import * ,
root = tk(), root = Tk(), root = tk.Tk(), root = tk.Tk(), root = Tk.tk()
root = TK.TK()
这是我在 PyCharm 中运行的代码:
from tkinter import *
import tkinter
top = Tk()
def helloCallBack():
print( "Hello Python", "Hello World")
B = tkinter.Button(top, text ="Hello", command = helloCallBack)
B.pack()
top.mainloop()
这些都在这里不起作用
请您参考如下方法:
好的。首先:
你不应该做的事:
在生产中,如果你不确定一个模块是被调用的方式(这可能取决于安装的 Python 版本),你不应该像那样将所有导入放在一起,因为如果一个失败它将引发导入错误,这将使您的运行时崩溃。执行以下操作:
try:
import Tkinter
except ImportError: # Python 3.x present
import tkinter
但是在您的情况下,您已经知道您拥有 Python 3,所以这不是问题。只需使用正确的(继续阅读下一节)。
推荐你做什么:
如果您使用的是 Python 2.x:
模块名为 Tkinter。您可以执行 from Tkinter import * 并且 Tk 将被导入。
如果您使用的是 Python 3.x:
模块名为 tkinter。注意小写。你必须做 import tkinter;并使用 tkinter.Tk
理由
您可能想从已经发布在 SO 上的这个答案中阅读这个片段:
However, PEP8 has this to say about wildcard imports:
Wildcard imports ( from import * ) should be avoided
In spite of countless tutorials that ignore PEP8, the PEP8-compliant way to import would be something like this:
import tkinter as tkWhen importing in this way, you need to prefix all tkinter commands with tk. (eg: root = tk.Tk(), etc). This will make your code easier to understand at the expense of a tiny bit more typing. Given that both tkinter and ttk are often used together and import classes with the same name, this is a Good Thing. As the Zen of python states: "explicit is better than implicit".
Note: The as tk part is optional, but lets you do a little less typing: tk.Button(...) vs tkinter.Button(...)
完整答案:https://stackoverflow.com/a/11621141/4396006
为什么你的解释器不导入 Tk
我不确定为什么您的解释器不为该用法导入 Tk。您必须提供更多详细信息才能解决您的那部分问题。
编辑:from tkinter import * 行包括 tkinter 中的 __init__.py 文件的命名空间> 模块文件夹到你的文件中。因此你应该检查:
PyCharm 从哪里导入 tkinter 模块。您可以转到导入中的
tkinter字词,右键单击上下文菜单,然后转到:Go to --> Declaration(或者直接点击Ctrl+B).它应该带您到__init__.py文件,其中Tk应该是其中定义的一个类。运行文件时您的 Python 路径是否正在获取您在其中找到 Tk 模块的文件夹。
如果有任何问题,那可能是因为您的安装有问题。如果您告诉我们只有 from tkinter import * 不起作用或者 import tkinter; 我会很有帮助; tkinter.Tk 也没有定义。您应该进行全新安装。
为了帮助我们了解问题的根源,请尝试从终端或 Python 控制台运行相同的代码,看看会发生什么。
