Tkinter messagebox without window?

前端 未结 4 1743
别那么骄傲
别那么骄傲 2020-11-30 10:08

I want to show an info window in my python script running on ubuntu. I\'m using the following code:

import tkMessageBox
tkMessageBox.showinfo(\"Say Hello\",          


        
相关标签:
4条回答
  • 2020-11-30 10:16

    For Python 3:

    import tkinter, tkinter.messagebox
    
    def messagebox(title, text):
        root = tkinter.Tk()
        root.withdraw()
        tkinter.messagebox.showinfo(title, text)
        root.destroy()
    

    With native Windows support when pywin32 is installed:

    try:
        from win32ui import MessageBox
    except ImportError:
        import tkinter, tkinter.messagebox
        def MessageBox(text, title):
            root = tkinter.Tk()
            root.withdraw()
            tkinter.messagebox.showinfo(title, text)
            root.destroy()
    
    0 讨论(0)
  • 2020-11-30 10:31

    Tkinter must have a root window. If you don't create one, one will be created for you. If you don't want this root window, create it and then hide it:

    import Tkinter as tk
    root = tk.Tk()
    root.withdraw()
    tkMessageBox.showinfo("Say Hello", "Hello World")
    

    Your other choice is to not use tkMessageBox, but instead put your message in the root window. The advantage of this approach is you can make the window look exactly like you want it to look.

    import Tkinter as tk
    root = tk.Tk()
    root.title("Say Hello")
    label = tk.Label(root, text="Hello World")
    label.pack(side="top", fill="both", expand=True, padx=20, pady=20)
    button = tk.Button(root, text="OK", command=lambda: root.destroy())
    button.pack(side="bottom", fill="none", expand=True)
    root.mainloop()
    

    (personally I would choose a more object-oriented approach, but I'm trying to keep the code small for this example)

    0 讨论(0)
  • 2020-11-30 10:34

    To avoid a "flash" as the root window is created, use this slight variation on the accepted answer:

    import Tkinter as tk
    root = tk.Tk()
    root.overrideredirect(1)
    root.withdraw()
    tkMessageBox.showinfo("Say Hello", "Hello World")
    
    0 讨论(0)
  • 2020-11-30 10:35

    Import messagebox individually. For example:

    from tkinter import *
    import tkinter.messagebox
    

    or

    from tkinter import messagebox
    
    0 讨论(0)
提交回复
热议问题