首页 > 解决方案 > 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. I'm getting what I want when I run it in my system, but when I'm running it in colab its not working.

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.

标签: pythontkinter

解决方案


当您看到Tk()时,它是文件夹中文件中Tk()存在的类的实例。__init__.pytkinter

由于您已经导入了 tkinter,因此您必须指定tkinter.Tk()创建一个Tk()

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

在某些程序中,您还可以看到tk.Tk(). 这是因为模块tkinter被导入为tk

import tkinter as tk

见源代码tkinter

在第 2273 行__init__.py,您可以看到:

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):

        ...

推荐阅读