简体   繁体   中英

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.

When you see Tk() , it is an instance of Tk() class present in __init__.py file in tkinter folder.

Since you have imported tkinter, you have to specify tkinter.Tk() to create a instance of 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() . This is because the module tkinter is imported as tk :

import tkinter as tk

See the source code of tkinter

At line 2273 in __init__.py , you can see:

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

    from tkinter import *

by using this it will work

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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