Search code examples
pythonfiletexttkintertkinter-entry

TypeError: unsupported operand type(s)s for +: 'StringVar' and 'str' // Create a text file


I'm trying to create a script that creates a text file, and the name of that text file corresponds to what was entered by the user. Here is my code:

from tkinter import*

fenetre = Tk()
def creation():
    open(f1 + '.txt', "w")
Label1 = Label(fenetre, text = 'Nom de votre classe :')
Label1.pack(side = LEFT, padx = 5, pady = 5)
f1 = StringVar()
Champ = Entry(fenetre, textvariable= f1, bg ='bisque', fg='maroon')
Champ.focus_set()
Champ.pack(side = LEFT, padx = 5, pady = 5)
Bouton = Button(fenetre, text ='Valider', command = creation())
Bouton.pack(side = LEFT, padx = 5, pady = 5)
fenetre.mainloop()

But it doesn't work and gives the following error:

TypeError: unsupported operand type(s)s for +: 'StringVar' and 'str'

I succeeded to create the file once, but it didn't got a name.


Solution

  • You need to call f1.get() when you want to use the value. f1 itself is not a string, but rather an object that can hold a string. Calling the get() method on it returns the actual string it is holding.

    def creation():
        open(f1.get() + '.txt', "w")