首页 > 解决方案 > 我在 tkinter 中使用 messagebox.askokcancel 函数时遇到问题

问题描述

我试图在完成某个操作后弹出一条消息,但确定按钮不起作用。

def delete_all_songs():
    if messagebox.askokcancel("Delete all Songs","Are you sure you want to delete all Songs"):
        print("doing")
        filelisttodelete = [f for f in os.listdir("C:/MusicPlayer/Songs/") if f.endswith(".mp3")]
        for f in filelisttodelete:
            os.remove(os.path.join("C:/MusicPlayer/Songs/", f))

        songs_box.delete(0, END)
        pygame.mixer.music.stop()
    else:
        pass

标签: pythontkinterpopupmessagebox

解决方案


函数“ askokcancel()...返回一个布尔值:True 表示“OK”或“Yes”选择,False 表示“No”或“Cancel”选择”——你必须使用它的返回值来弹出消息。这是一个独立的可运行示例:

from tkinter import *
from tkinter import messagebox

def delete_all_songs():
    if messagebox.askokcancel("Delete all Songs",
                              "Are you sure you want to delete all Songs?"):
#        filelisttodelete = [f for f in os.listdir("C:/MusicPlayer/Songs/")
#                             if f.endswith(".mp3")]
#        for f in filelisttodelete:
#            os.remove(os.path.join("C:/MusicPlayer/Songs/", f))
#
#        songs_box.delete(0, END)
#        pygame.mixer.music.stop()
        messagebox.showinfo("Info", "All Songs Deleted")
    else:
        messagebox.showinfo("Info", "Song Deletion Canceled")

win = Tk()
Button(win, text="Test", command=delete_all_songs).pack()
Button(win, text="Quit", command=win.quit).pack()
win.mainloop()


推荐阅读