如何使用tkinter创建消息框?

12

我一直在尝试在tkinter中构建一个相当简单的消息框,它有"YES"和"NO"按钮。当我点击"YES"按钮时,它必须内部地去写入"Yes"到一个文件中。同样,当点击"NO"时,需要写入"No"到文件中。我该怎么做呢?


4
对我来说这听起来像是一个不错的作业问题... 那么,你目前有什么进展了吗? - balpha
5个回答

21
你可以使用Python 2.7中的模块tkMessageBox或对应于Python 3的tkinter.messagebox模块。
看起来askquestion()正是你需要的函数,它甚至会为你返回字符串"yes""no"

1
tkinter.messagebox在我的Ubuntu 12.04 Python中无法工作。 - Ajoy
1
@Ajoy 请检查您使用的Python版本,如果是2.x版本,则可能需要执行tkMessageBox - Tyler

12

以下是如何在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()

链接到其他类型的消息框:http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/tkMessageBox.html - Nande

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')

1
您可以使用Tkinter中的消息框
# 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()

有不同类型的消息框或函数名称:

  1. showinfo():向用户显示相关信息。
  2. showwarning():向用户显示警告。
  3. showerror():向用户显示错误消息。
  4. askquestion():询问问题,用户必须回答是或否。
  5. askokcancel():确认用户对某些应用程序活动的操作。
  6. askyesno():用户可以对某些操作回答是或否。
  7. askretrycancel():询问用户是否再次执行特定任务。
  8. Message:创建默认信息框,或与showinfo框相同。
messagebox.Message(master=None, **options)
# Create a default information message box.

你甚至可以传递自己的标题、消息,甚至修改其中的按钮文本。

你可以在消息框中传递以下内容:

  • 标题:该参数是一个字符串,用作消息框的标题。
  • 消息:该参数是要在消息框中显示的字符串消息。
  • 选项:有两个可用选项:
    1. 默认:此选项用于指定消息框中的默认按钮,如 ABORT、RETRY 或 IGNORE。
    2. 父级:此选项用于指定要在其上方显示消息框的窗口。

我在这个答案中使用了以下链接:


-1

你不需要任何其他模块来完成这个任务!

>>> from tkinter import messagebox
>>> messagebox.askokcancel("Title", "Message")
True

当用户按下“确定/重试/是”按钮时,它返回True,否则返回False。

其他可用的函数:

  • askokcancel()
  • askyesno() 或 askquestion()(相同)
  • askretrycancel()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接