如何在python中使用tkinter创建弹出窗口?

时间:2018-04-24 18:07:05

标签: python tkinter

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

2 个答案:

答案 0 :(得分:0)

最简单的解决方案是导入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()

答案 1 :(得分:-1)

快速Google,从代码编辑 https://pythonprogramming.net/tkinter-popup-message-window/

import tkinter as tk

percentage = 0.3

def popupmsg(msg):
    popup = tk.Toplevel()
    popup.title("!")
    label = tk.Label(popup, text=msg) #Can add a font arg here
    label.pack(side="top", fill="x", pady=10)
    B1 = tk.Button(popup, text="Okay", command = popup.destroy)
    B1.pack()
    popup.mainloop()

popupmsg('You have a discount of ' + str(percentage*100) + '%')