44
import TkMessageBox

When I import TkMessageBox it displays the messsge 'ImportError: No module named 'TkMessageBox'.

As far as I know im using python 3.3.2 and Tk 8.5.

Am I using the wrong version of python or importing it wrong ?

Any answers would be extremely useful. Alternatively is there something similar in the version i am using?

Billal Begueradj
  • 20,717
  • 43
  • 112
  • 130
Tom Lowbridge
  • 879
  • 3
  • 9
  • 17

5 Answers5

88

In Python3.x things have changed a little bit:

   >>> import tkinter
   >>> import tkinter.messagebox
   >>>

I mean what we call tkMessageBox in Python2.x becomes tkinter.messagebox in Python3.x

Billal Begueradj
  • 20,717
  • 43
  • 112
  • 130
  • 3
    ... so you can invoke like: `tkinter.messagebox.showinfo("Congratulations", "You won!")` – s2t2 May 28 '19 at 16:24
  • Care to explain your action? https://stackoverflow.com/questions/61939967/pattern-matching-instanceof –  May 22 '20 at 04:57
  • Sorry, I had to read your question more carefully. I voted to re-open your post and I upvoted it @Trey – Billal Begueradj May 22 '20 at 07:38
11

If you don't want to have to change the code for Python 2 vs Python 3, you can use import as:

try:
    from tkinter import messagebox
except ImportError:
    # Python 2
    import tkMessageBox as messagebox

:edit: However, tkinter is in a separate package in Debian due to Debian policies causing code above to fall back to Python 2 incorrectly. So instead, you should do:

import sys
if sys.version_info.major >= 3:
    from tkinter import messagebox
else:
    import tkMessageBox as messagebox

Then using messagebox as follows will work in either version:

messagebox.showerror("Error", "Message.")
Poikilos
  • 1,050
  • 8
  • 11
8

In Python 2.x, to import, you'd say import tkMessageBox. But in Python 3.x, it's been renamed to import tkinter.messagebox.

Hope it helped :))

Hung Truong
  • 339
  • 2
  • 6
  • 19
4

for python 3.x

import tkinter

import tkinter.messagebox

Suraj Verma
  • 463
  • 6
  • 8
0

from tkinter import messagebox sous Python 3 messagebox.showinfo(title=None, message=None, **options)

  • 2
    Welcome to stackoverflow. Thanks you for your contribution, but please provide further explanations on your solution: don't just give a fix, explain what it does and what was wrong – Roim May 28 '20 at 13:14