简体   繁体   English

tkinter 消息框的问题

[英]issue with tkinter messagebox

I'm using several tkinter messageboxes in my code.我在我的代码中使用了几个 tkinter 消息框。 But ive noticed a problem with the showinfo messageboxes I've used in my code.但是我注意到我在代码中使用的showinfo消息框有问题。 Basically, I want a function to be called when the ok on the messagebox is pressed.基本上,我希望在按下消息框上的ok时调用一个函数。 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.但是,看起来当我按 x 图标关闭消息框时,该函数仍然被调用。 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?我的问题是,我应该怎么做才能在按下 x 图标时不调用该函数?

There are different types of messagebox , the one your using here is not what you actually should be using for your case.有不同类型的messagebox ,您在此处使用的那个不是您实际应该为您的案例使用的。 What you want is something called askyesno , or something that is prefixed by 'ask' because your code depend upon the users action.您想要的是名为askyesno东西,或者以“ask”为前缀的东西,因为您的代码取决于用户的操作。 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 .在这里,如果您单击“是”按钮, askyesno与其他“ask”前缀函数一样将返回True1 ,否则它将返回False0

Also just something I realized now, showinfo , like other 'show' prefixed messagebox function, returns 'ok' either you press the button or close the window.也只是我现在意识到的一些事情, showinfo ,就像其他showinfo 'show' 前缀的消息框函数一样,无论您按下按钮还是关闭窗口,都会返回'ok'

Some more 'ask' prefixed messageboxes ~ askokcancel , askquestion , askretrycancel , askyesnocancel .一些更多'ask'前缀的消息框~ askokcancelaskquestionaskretrycancelaskyesnocancel Take a look here看看这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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