首页 > 解决方案 > 将 Python gui 窗口放在前面?

问题描述

我正在尝试使用 Python 的 gui 模块之一来检索用户的 Twitter 用户名和密码:

这是我的第一次尝试(使用easygui):

import easygui
username = easygui.enterbox("Enter your Twitter username")
password = easygui.passwordbox("Enter your Twitter password")

这是我的第二次尝试(使用 tkinter):

import tkinter as tk
from tkinter import simpledialog

application_window = tk.Tk()
application_window.attributes("-topmost", True)
username = simpledialog.askstring("Input", "What is your Twitter username?")
password = simpledialog.askstring("Input", "What is your Twitter password?", show="*")
application_window.destroy()

目前,这两个 gui 都不会自动出现。相反,我的 Windows 任务栏上会出现一个 Python 图标,我必须单击该图标才能显示 gui。是否有任何编程方式可以使 gui 自动弹出?或者也许我可以使用另一个模块来实现这一点?

标签: pythontkintereasygui

解决方案


simpledialog 模块创建了一个新的 Toplevel 窗口,这是您想要提出的那个,而不是根窗口。

simpledialog当您已经运行 tkinter GUI 时效果最佳。我认为你会更好easygui,因为它实际上使用了一个 tkinter Tk 实例:

import easygui

fieldNames = ["Username", "Password"]
values = easygui.multpasswordbox("Enter Twitter information", "Input", fieldNames)
if values:
    username, password = values
else:
    # user pushed "Cancel", the esc key, or Xed out the window
    username, password = None, None
print(username, password)

如果这不起作用,easygui 可以使用最上面的技巧:

import easygui

fieldNames = ["Username", "Password"]
mb = easygui.multpasswordbox("Enter Twitter information", "Input", fieldNames, run=False)
mb.ui.boxRoot.attributes("-topmost", True)
mb.run()
if mb.values:
    username, password = mb.values
else:
    # user pushed "Cancel", the esc key, or Xed out the window
    username, password = None, None
print(username, password)

或者只是制作自己的对话。


推荐阅读