python - 如何在 python 中使用 tkinter 创建弹出窗口?
问题描述
我的程序是一个库存管理系统。因此,当它是特定月份时,我希望向用户显示一个弹出窗口,指示应将特定百分比折扣应用于产品。
解决方案
最简单的解决方案是导入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()
推荐阅读
- python - Numpy 2d ndarray 按给定的特定二维数组排序
- html - 如何将父块包裹在移动的子块周围?
- java - PreparedStatement java的第二个参数-ORDER BY-语法错误
- r - 具有 4 个变量的 r 中的分组条形图
- c# - Unity 2D How to Make a Multi Input Attack
- c# - ContentView 获取选择器选择的值
- c - char** argv 作为字符串数组传递
- c - 如何将标准输入和标准输出附加到 call_usermodehelper 调用的用户进程
- html - 4 个响应式 div 在选项卡和移动设备上未正确显示
- python - Tensorflow/Spyder 重置没有错误