简体   繁体   English

没有窗口的 Tkinter 消息框?

[英]Tkinter messagebox without window?

I want to show an info window in my python script running on ubuntu.我想在运行在 ubuntu 上的 python 脚本中显示一个信息窗口。 I'm using the following code:我正在使用以下代码:

import tkMessageBox
tkMessageBox.showinfo("Say Hello", "Hello World")

This works, but there's an empty window displayed, with the message box on top.这有效,但显示了一个空窗口,消息框位于顶部。 How can I get rid of the window and just centre the message box on the screen (window manager is gnome 2)?如何摆脱窗口并仅将消息框居中显示在屏幕上(窗口管理器是 gnome 2)?

This is just to display some info from a command line script (a password which is why I don't want to just echo it to the console).这只是为了显示来自命令行脚本的一些信息(密码,这就是为什么我不想将它回显到控制台)。

Tkinter must have a root window. Tkinter 必须有一个根窗口。 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.您的另一个选择是使用 tkMessageBox,而是将您的消息放在根窗口中。 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) (我个人会选择一种更面向对象的方法,但我试图保持这个例子的代码很小)

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

For Python 3:对于 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:安装pywin32时具有本机 Windows 支持:

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

Import messagebox individually.单独导入消息框。 For example:例如:

from tkinter import *
import tkinter.messagebox

or要么

from tkinter import messagebox

This works for python 3这适用于python 3

from tkinter import *
from tkinter import messagebox

root = Tk()
root.withdraw()
messagebox.showinfo("Window Title", "Your Message")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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