Reputation: 159261
I've been trying to build a fairly simple message box in tkinter that has "YES" and "NO" buttons. When I push the "YES" button internally it must go and write YES to a file. Similarly, when "NO" is pushed, NO must be written to a file. How can I do this?
Upvotes: 14
Views: 67180
Reputation: 1148
You can use message box
from Tkinter using
# 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.
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:
messagebox.Message(master=None, **options)
# Create a default information message box.
You can even pass your own title and message in it.
Things you can pass in the message boz:
Links i have used for this answer:
Upvotes: 1
Reputation: 727
Here's how you can ask a question using a message box in Python 2.7. You need specifically the module 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()
Upvotes: 13
Reputation: 22116
You can use the module tkMessageBox for Python 2.7 or the corresponding version for Python 3 called tkinter.messagebox
.
It looks like askquestion()
is exactly the function that you want. It will even return the string "yes"
or "no"
for you.
Upvotes: 22
Reputation: 81
You can assign the return value of the askquestion
function to a variable, and then you simply write the variable to a file:
from tkinter import messagebox
variable = messagebox.askquestion('title','question')
with open('myfile.extension', 'w') as file: # option 'a' to append
file.write(variable + '\n')
Upvotes: 8