如何用tkinter创建消息框?
我一直在尝试用tkinter创建一个简单的消息框,里面有“YES”和“NO”两个按钮。当我点击“YES”按钮时,程序内部需要把“YES”写入一个文件。同样地,当点击“NO”时,也要把“NO”写入文件。我该怎么做呢?
5 个回答
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')
13
下面是如何在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()
22
你可以使用模块 tkMessageBox,如果你用的是Python 2.7,或者用Python 3的话,可以用对应的版本 tkinter.messagebox
。
看起来 askquestion()
正是你需要的功能。它会返回字符串 "yes"
或 "no"
给你。