简体   繁体   中英

issue with tkinter messagebox

I'm using several tkinter messageboxes in my code. But ive noticed a problem with the showinfo messageboxes I've used in my code. Basically, I want a function to be called when the ok on the messagebox is pressed. Also, the user can choose not to proceed by just closing the messagebox. But, it looks like when I press the x icon to close the messagebox, the function is still called. Here is a minimum reproducible code to explain what i mean.

from tkinter import *
from tkinter import messagebox

root = Tk()

def func() :
    Label(root,text="This is the text").pack()

msg = messagebox.showinfo("Loaded","Your saved state has been loaded")
if msg == "ok" :
    func()

root.mainloop()

My question is, What should i do so that the function is not called when the x icon is pressed?

There are different types of messagebox , the one your using here is not what you actually should be using for your case. What you want is something called askyesno , or something that is prefixed by 'ask' because your code depend upon the users action. So you want to 'ask' the user, like:

from tkinter import *
from tkinter import messagebox

root = Tk()

def func() :
    Label(root,text="This is the text").pack(oadx=10,pady=10)

msg = messagebox.askyesno("Loaded","Your saved state has been loaded")
if msg: #same as if msg == True:
    func()

root.mainloop()

Here, askyesno like other 'ask' prefixed functions will return True or 1 if you click on the 'Yes' button, else it will return False or 0 .

Also just something I realized now, showinfo , like other 'show' prefixed messagebox function, returns 'ok' either you press the button or close the window.

Some more 'ask' prefixed messageboxes ~ askokcancel , askquestion , askretrycancel , askyesnocancel . Take a look here

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