如何使用tkinter创建消息框?

use*_*646 9 python tkinter messagebox

我一直在尝试在tkinter中构建一个相当简单的消息框,其中包含"YES"和"NO"按钮.当我在内部按下"YES"按钮时,它必须转到并向文件写入YES.类似地,当按下"NO"时,必须将NO写入文件.我怎样才能做到这一点?

Mat*_*rog 19

您可以使用模块tkMessageBox for Python 2.7或相应的Python 3版本调用tkinter.messagebox.

它看起来就像askquestion()你想要的功能.它甚至会返回字符串"yes""no"为您.


小智 11

以下是使用Python 2.7中的消息框提问的方法.你需要专门的模块tkMessageBox.

from Tkinter import *
import tkMessageBox


root = Tk().withdraw()  # hiding the main window
var = tkMessageBox.askyesno("Title", "Your question goes here?")

filename = "log.txt"

f = open(filename, "w")
f.write(str(var))
print str(var) + " has been written to the file " + filename
f.close()
Run Code Online (Sandbox Code Playgroud)


小智 8

您可以将askquestion函数的返回值赋给变量,然后只需将变量写入文件:

from tkinter import messagebox

variable = messagebox.askquestion('title','question')

with open('myfile.extension', 'w') as file: # option 'a' to append
    file.write(variable + '\n')
Run Code Online (Sandbox Code Playgroud)