我一直在尝试在tkinter中构建一个相当简单的消息框,它有"YES"和"NO"按钮。当我点击"YES"按钮时,它必须内部地去写入"Yes"到一个文件中。同样,当点击"NO"时,需要写入"No"到文件中。我该怎么做呢?
我一直在尝试在tkinter中构建一个相当简单的消息框,它有"YES"和"NO"按钮。当我点击"YES"按钮时,它必须内部地去写入"Yes"到一个文件中。同样,当点击"NO"时,需要写入"No"到文件中。我该怎么做呢?
tkinter.messagebox
模块。askquestion()
正是你需要的函数,它甚至会为你返回字符串"yes"
或"no"
。tkMessageBox
。 - Tyler以下是如何在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()
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')
消息框
。# For python 3 or above
from tkinter import messagebox
# For python less than 3
from Tkinter import *
import tkMessageBox
以下是基本语法:
messagebox.Function_Name(title, message [, options])
消息框是模态的,根据用户的选择返回(True、False、OK、None、Yes、No)的子集。
因此,要获取消息框的值,只需要将该值存储在变量中。下面给出一个示例:
res=mb.askquestion('Exit Application', 'Do you really want to exit')
if res == 'yes' :
root.destroy()
有不同类型的消息框或函数名称:
messagebox.Message(master=None, **options)
# Create a default information message box.
你甚至可以传递自己的标题、消息,甚至修改其中的按钮文本。
你可以在消息框中传递以下内容:
我在这个答案中使用了以下链接:
你不需要任何其他模块来完成这个任务!
>>> from tkinter import messagebox
>>> messagebox.askokcancel("Title", "Message")
True
当用户按下“确定/重试/是”按钮时,它返回True,否则返回False。
其他可用的函数: