简体   繁体   English

Python('module' 对象不可调用)Tkinter

[英]Python('module' object is not callable )Tkinter

I'm getting this issue as mentioned in the title.我遇到了标题中提到的这个问题。 I'm trying to run a file to print hello world in the widget.我正在尝试运行一个文件来在小部件中打印 hello world。 I'm getting what I want when I run it in my system, but when I'm running it in colab its not working.当我在我的系统中运行它时,我得到了我想要的东西,但是当我在 colab 中运行它时它不起作用。

Code:代码:

import tkinter

root = tk()

myLabel = Label(root, text="Hello World!")

myLabel.pack()

root.mainloop()

Output:输出:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-18-db74150bd164> in <module>()
      1 import tkinter
      2 
----> 3 root = tk()
      4 
      5 myLabel = Label(root, text="Hello World!")

TypeError: 'module' object is not callable

I tried changing tk into various forms( Tk, tK, Tkinter, tKinter ), but it isn't working anyhow.我尝试将tk更改为各种形式( Tk, tK, Tkinter, tKinter ),但无论如何它都不起作用。

When you see Tk() , it is an instance of Tk() class present in __init__.py file in tkinter folder.当你看到Tk()它是一个实例Tk()存在于类__init__.py文件tkinter文件夹中。

Since you have imported tkinter, you have to specify tkinter.Tk() to create a instance of Tk()既然已经导入了tkinter.Tk() ,就必须指定tkinter.Tk()来创建Tk()的实例

import tkinter
root = tkinter.tk()
myLabel = Label(root, text="Hello World!")
myLabel.pack()
root.mainloop()

In some programs, you can also see tk.Tk() .在某些程序中,您还可以看到tk.Tk() This is because the module tkinter is imported as tk :这是因为模块tkinter被导入为tk

import tkinter as tk

See the source code of tkintertkinter的源代码

At line 2273 in __init__.py , you can see:__init__.py第 2273 行,您可以看到:

class Tk(Misc, Wm):
    """Toplevel widget of Tk which represents mostly the main window
    of an application. It has an associated Tcl interpreter."""
    _w = '.'

    def __init__(self, screenName=None, baseName=None, className='Tk',
                 useTk=True, sync=False, use=None):

        ...

There are some errors:有一些错误:

import tkinter as tk 

root = tk.Tk() # tk() you can't call a module, write tk.Tk() instead.
myLabel = tk.Label(root, text="Hello World!") # add tk.
myLabel.pack()
root.mainloop()

you can just import tkinter as您可以将 tkinter 导入为

    from tkinter import *

by using this it will work通过使用它,它将起作用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM