Kenan Kazim Kenan Kazim - 1 month ago 7
Python Question

Getting data from tkinter entry and write on txt file

I want to get data from tkinter entry and write that on txt file. And I have written this code but It does not work. Where do I mistake? I am beginner and I now I have written so complicated and I now that there are a lot of way to do this. Please help me with it.

#!/usr/bin/env python

#-*- coding: utf-8 -*-


from tkinter import *


root = Tk()


label_1 = Label(root, text="Email:")
label_2 = Label(root, text="Password:")
entry_1 = Entry(root, textvariable = "var")
entry_2 = Entry(root)


label_1.grid(row=0, sticky=E)
label_2.grid(row=1, sticky=E)

entry_1.grid(row=0, column=1)
entry_2.grid(row=1, column=1)

c = Checkbutton(root, text="Keep me logged in")
c.grid(columnspan=2)

var = StringVar()
var.set("Email:" , entry_1)
a = var.get()
data = open("/home/guillermo/Desktop/data.txt", "w")
data.write(a)
data.close()

root.mainloop()

Answer

Your code demonstrates a misunderstanding of several concepts. First, an Entry widget's textvariable is supposed to be a variable (specifically, a tkinter.StringVar(), as you create later), not a hard-coded string. Second, you are setting the StringVar() you eventually create to... well, nothing, because you send its set() method two arguments where it's only supposed to have one. Perhaps you're used to the print() function, which takes an arbitrary number of arguments and applies a separator, end, and so on. Simply sending multiple arguments to a function does not perform a string join on them. Next, one of the arguments you are sending is entry_1 itself, which is an Entry widget. Such a widget can contain text, but it isn't text per se. You have to access its textvariable (if you provided one) or simply get its contents. If you're not doing anything particularly complex with it, you don't need a textvariable at all.

These errors have been repaired below:

from tkinter import *

root = Tk()

label_1 = Label(root, text="Email:")
label_2 = Label(root, text="Password:")
entry_1 = Entry(root)
entry_2 = Entry(root)


label_1.grid(row=0, sticky=E)
label_2.grid(row=1, sticky=E)

entry_1.grid(row=0, column=1)
entry_2.grid(row=1, column=1)

c = Checkbutton(root, text="Keep me logged in")
c.grid(columnspan=2)

with open("/home/guillermo/Desktop/data.txt", "w") as data:
    data.write('Email: ' + entry_1.get())

root.mainloop()
Comments