How to determine whether the user clicked on OK or Cancel in a MessageBox?
In a MessageBox, a variable can usually be used to store the result of the button pressed by the user. The specific implementation may vary depending on the programming language and framework used. For example, in Python’s tkinter library, you can check if the user pressed OK or Cancel in a MessageBox.
import tkinter as tk
from tkinter import messagebox
def show_message_box():
result = messagebox.askquestion("确认", "您确定要执行此操作吗?")
if result == 'yes':
print("用户点击了确认按钮")
else:
print("用户点击了取消按钮")
root = tk.Tk()
root.geometry("200x200")
button = tk.Button(root, text="显示MessageBox", command=show_message_box)
button.pack()
root.mainloop()
In the above code, use the messagebox.askquestion method to display a MessageBox with a confirm and cancel button. The method will return the result of the button the user pressed – ‘yes’ if they clicked confirm, and ‘no’ if they clicked cancel. Based on this result, we can perform the corresponding action.