-2

I have this code that creates a gui with value entry box. but how do I make the it write into file when I push the button?

from tkinter import *
from tkinter import messagebox
from tkinter import simpledialog

msg = messagebox
sdg = simpledialog

root = Tk()
w = Label(root, text="My Program")
w.pack()

msg.showinfo("welcome", "hi. ")

name = sdg.askstring("Name", "What is you name?")
age = sdg.askinteger("Age", "How old are you?")
  • Have you looked at any tutorials? There must be hundreds of tutorials and websites that show how to write to a file. – Bryan Oakley Feb 03 '18 at 15:45

1 Answers1

0

To write text to a file:

filename = "output.txt"

with open(filename, "w") as f:
    f.write("{} - {}".format(name, age))

Check out the docs to learn about reading/writing text files.

Your code just shows dialogs, if you want to associate an action with a button, you'll need to run a main loop:

from tkinter import *
from tkinter import messagebox as msg
from tkinter import simpledialog as sdg


def btn_action():
    msg.showinfo("welcome", "hi. ")
    name = sdg.askstring("Name", "What is you name?")
    age = sdg.askinteger("Age", "How old are you?")

    filename = "output.txt"
    with open(filename, "w") as f:
        f.write("{} - {}".format(name, age))

root = Tk()
w = Label(root, text="My Program")
w.pack()
b = Button(root, text="Ask", command=btn_action)
b.pack()

root.mainloop()

See this tutorial to learn about tkinter.

Bober
  • 479
  • 3
  • 6