[英]How to create a message box with tkinter?
I've been trying to build a fairly simple message box in tkinter that has "YES" and "NO" buttons.我一直在尝试在 tkinter 中构建一个具有“是”和“否”按钮的相当简单的消息框。 When I push the "YES" button internally it must go and write YES to a file.
当我在内部按下“是”按钮时,它必须是 go 并将“是”写入文件。 Similarly, when "NO" is pushed, NO must be written to a file.
类似地,当按下“NO”时,必须将 NO 写入文件。 How can I do this?
我怎样才能做到这一点?
You can use the module tkMessageBox for Python 2.7 or the corresponding version for Python 3 called tkinter.messagebox
.您可以使用 Python 2.7 的模块tkMessageBox或 Python 3 的相应版本,称为
tkinter.messagebox
。
It looks like askquestion()
is exactly the function that you want.看起来
askquestion()
正是您想要的功能。 It will even return the string "yes"
or "no"
for you.它甚至会为您返回字符串
"yes"
或"no"
。
Here's how you can ask a question using a message box in Python 2.7.以下是在 Python 2.7 中使用消息框提问的方法。 You need specifically the module
tkMessageBox
.您特别需要模块
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()
You can assign the return value of the askquestion
function to a variable, and then you simply write the variable to a file:您可以将
askquestion
函数的返回值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')
You don't need any other modules to do this!你不需要任何其他模块来做到这一点!
from tkinter import messagebox
messagebox.showerror("Title", "Message")
You can use message box
from Tkinter using您可以使用来自 Tkinter 的
message box
# For python 3 or above
from tkinter import messagebox
# For python less than 3
from Tkinter import *
import tkMessageBox
Here's the basic syntax:这是基本语法:
messagebox.Function_Name(title, message [, options])
The message boxes are modal and will return a subset of (True, False, OK, None, Yes, No) based on the user's selection.消息框是模态的,将根据用户的选择返回(True、False、OK、None、Yes、No)的子集。
So to get the value of message box you just need to store the value in a variable.因此,要获取消息框的值,您只需将值存储在变量中即可。 An example is given below:
下面给出一个例子:
res=mb.askquestion('Exit Application', 'Do you really want to exit')
if res == 'yes' :
root.destroy()
There are different type of message boxes or Function_name:有不同类型的消息框或 Function_name:
messagebox.Message(master=None, **options)
# Create a default information message box.
You can even pass your own title, message and even modify the button text in it.您甚至可以传递自己的标题、消息甚至修改其中的按钮文本。
Things you can pass in the message boz:您可以在消息 boz 中传递的内容:
Links i have used for this answer:我用于此答案的链接:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.