简体   繁体   中英

How do I create a pop up window using tkinter in python?

My program is a stock management system. So, when it is a specific month I want a pop-up window to be shown to the user indicating that a specific percentage discount should be applied to the product.

The simplest solution is to import datetime and find out what month it is. Then check the current month to see if you want to display a message for that month.

Tkinter comes with several options for pop up messages. I think for your specific question you want the showinfo() method.

Here is a simple example:

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

Update:

In an attempt to help both the OP and the other person answer the question I have reformatted their answer to something more functional.

@George Sanger: Keep in mind that the mainloop() should only be called on the instance of Tk() that all tkinter applications are build off of. The use of Toplevel is so that you can create new windows after you have already created a main window with 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()

Quick Google, edit from code on 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) + '%')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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