简体   繁体   English

我可以通过单击 messagebox.showinfo 中的“确定”来拨打 function 吗?

[英]Can I call a function by clicking 'OK' in messagebox.showinfo?

I have added a message box in my code and I want to call a function defined earlier when clicking the 'OK' button in the message box.我在我的代码中添加了一个消息框,我想在单击消息框中的“确定”按钮时调用之前定义的 function。 Is there any way to achieve this?有什么办法可以做到这一点? Thanks in advance.提前致谢。

messagebox.showinfo('Correct', 'Correct!\nClick OK to continue')

When you make a showinfo box, it actually halts your script until you press OK.当您创建一个 showinfo 框时,它实际上会暂停您的脚本,直到您按 OK。 All you will need to do is put the function you want right after it.您需要做的就是在它之后放置您想要的功能。

See this example:看这个例子:

import tkinter as tk
from tkinter import messagebox

def go():
    messagebox.showinfo('Correct', 'Correct!\nClick OK to continue')
    print('yeah')

root = tk.Tk()

btn = tk.Button(root, text='click', command=go)
btn.pack()

root.mainloop()

If you run that, you will see the print('yeah') only happens when the user clicks OK.如果你运行它,你会看到print('yeah')只有在用户点击 OK 时才会发生。 So, you can do something similar and call the function where I have put the print.所以,你可以做类似的事情并调用我放置打印的函数。

I had a similar problem and looked for a simple code.我遇到了类似的问题,正在寻找一个简单的代码。 You can use:您可以使用:

from tkinter import Tk,messagebox

root=Tk() 
result=messagebox.showinfo('Correct','Correct!')
root.destroy()
go()

I used root.destroy() because sometimes I had problems closing the popup window.我使用 root.destroy() 因为有时我在关闭弹出窗口 window 时遇到问题。

In tkinter.messagebox.showinfo your only option is to press OK or close the tkinter popup window, both has the same effect and returns a string "ok".在 tkinter.messagebox.showinfo 中,您唯一的选择是按 OK 或关闭 tkinter 弹出窗口 window,两者具有相同的效果并返回字符串“ok”。

If you instead want to call a function only when you press yes use tkinter.messagebox.askyesno:如果您只想在按“是”时调用 function,请使用 tkinter.messagebox.askyesno:

from tkinter import Tk,messagebox

root=Tk() 
result=messagebox.askyesno('Correct','Correct!')
root.destroy()
if result==True:
    go()

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

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