没有窗口的 Tkinter 消息框? [英] Tkinter messagebox without window?

查看:42
本文介绍了没有窗口的 Tkinter 消息框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在运行在 ubuntu 上的 python 脚本中显示一个信息窗口.我正在使用以下代码:

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", "Hello World")

这行得通,但会显示一个空窗口,消息框位于顶部.如何摆脱窗口并仅将消息框居中显示在屏幕上(窗口管理器是 gnome 2)?

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

这只是为了显示命令行脚本中的一些信息(密码,这就是为什么我不想将其回显到控制台的原因).

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 必须有一个根窗口.如果你不创造一个,就会为你创造一个.如果你不想要这个根窗口,创建它然后隐藏它:

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

您的另一个选择是使用 tkMessageBox,而是将您的消息放在根窗口中.这种方法的优点是您可以使窗口看起来与您想要的完全一样.

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)

这篇关于没有窗口的 Tkinter 消息框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆