Reputation: 21
I've got a lot of experience with basic programming, but none with GUI programming, and I am teaching myself Python 3 with tkinter for that purpose. I've got some great answers by checking stackoverflow posts, but now I've got a problem that doesn't seem to have been covered. I want my program to get user input from an Entry widget and write that data to a file. After stripping out all nonessential lines, my current code is
from tkinter import *
from tkinter import ttk
root = Tk()
sheetid = StringVar()
def finish():
with open('C:/Python33/data.txt', 'w') as f:
f.write('first line of text\n')
with open('C:/Python33/data.txt', 'a') as f:
f.write(sheetid)
main = Frame(root).grid()
ttk.Entry(main, textvariable="sheetid").grid(row=0, column=1)
ttk.Button(main, text="Close", command=finish).grid(column=1)
root.mainloop()
I've previously used the Label widget to write the variable "sheetid"in a window, so I know the combination of Entry widget and the "Close" Button widget are working. The first write statement works, so I know my file-opening code is correct. The second write gives a run-time error:
TypeError: must be str, not StringVar.
Next I tried converting "sheetid" to a string, using
s = str(sheetid,'\n')
but this also returned a run-time error:
TypeError: coercing to str: need bytes, bytearray or buffer-like object, StringVar found.
Surely there is a way to do this, but my google search hasn't found it.
Thanks!
Upvotes: 0
Views: 3548
Reputation: 385970
You cannot use ..., textvariable="sheetid"
, you must use ..., textvariable=sheetid, ...
(notice the lack of quotes around sheetid
). And then, when you want to write the value out you must use sheetid.get()
.
Upvotes: 3