0

In my code, I have imported the main tkinter modules using the line:

import tkinter as tk

I can then reference tkinter modules for example as tk.Button().

I would like to also import the tkinter.messagebox module, which I am aware must be imported specifically.

However, I'd like to be able to reference it like tk.messagebox() to stay consistent with the rest of my code. As far as I can tell, there is no way to achieve this.

What I have tried include:

import tkinter.messagebox as tk.messagebox # Invalid syntax
import tkinter as tk
import tk.messagebox # No module named 'tk'
from tkinter import messagebox as tk.messagebox # Invalid syntax

Is there any way to import tkinter.messagebox to be referenced as tk.messagebox()?

jstri
  • 3
  • 1

1 Answers1

2

It can be done as below:

import tkinter as tk
import tkinter.messagebox

tk.messagebox.showinfo("INFO", "Hello World")
# or tkinter.messagebox.showinfo(...)

Note that you cannot use the module as a function, like tk.messagebox().

acw1668
  • 40,144
  • 5
  • 22
  • 34
  • For brevity's sake, I tend to to `import tkinter.messagebox as tkm` – JRiggles May 15 '23 at 15:45
  • @JRiggles, that would not be correctly answering the question. They want to stay consistent by sacrificing brevity. – SanguineL May 15 '23 at 15:47
  • @SanguineL I'm aware, I'm merely expressing my preference on the off-chance someone finds it helpful. I did not mean to suggest that acw1668 was incorrect in any way (they usually aren't!) – JRiggles May 15 '23 at 15:51
  • @JRiggles, gotcha. I, too, prefer brevity. – SanguineL May 15 '23 at 15:54