首页 > 解决方案 > 如何在 python 中使用 tkinter 创建弹出窗口?

问题描述

我的程序是一个库存管理系统。因此,当它是特定月份时,我希望向用户显示一个弹出窗口,指示应将特定百分比折扣应用于产品。

标签: pythontkinter

解决方案


最简单的解决方案是导入datetime并找出月份。然后检查当前月份以查看是否要显示该月份的消息。

Tkinter 带有几个用于弹出消息的选项。我认为对于您的具体问题,您需要该showinfo()方法。

这是一个简单的例子:

import tkinter as tk
from tkinter import messagebox
from datetime import datetime


this_month = datetime.now().month

root = tk.Tk()

tk.Label(root, text="This is the main window").pack()

# this will display pop up message on the start of the program if the month is currently April.
if this_month == 4:
    messagebox.showinfo("Message", "Some message you want the users to see")   

root.mainloop()

更新:

为了帮助 OP 和其他人回答这个问题,我将他们的答案重新格式化为更实用的东西。

@George Sanger:请记住,mainloop()应该只在Tk()所有 tkinter 应用程序都建立的实例上调用。的用途Toplevel是,您可以在已经使用Tk().

import tkinter as tk


percentage = 0.3

#tkinter applications are made with exactly 1 instance of Tk() and one mainloop()
root = tk.Tk()

def popupmsg(msg):
    popup = tk.Toplevel(root)
    popup.wm_title("!")
    popup.tkraise(root) # This just tells the message to be on top of the root window.
    tk.Label(popup, text=msg).pack(side="top", fill="x", pady=10)
    tk.Button(popup, text="Okay", command = popup.destroy).pack()
    # Notice that you do not use mainloop() here on the Toplevel() window

# This label is just to fill the root window with something.
tk.Label(root, text="\nthis is the main window for your program\n").pack()

# Use format() instead of + here. This is the correct way to format strings.
popupmsg('You have a discount of {}%'.format(percentage*100))

root.mainloop()

推荐阅读