0

I am currently trying to build a program that shows a ktinker interface with buttons, one of which (ecrire) will write in a file the current content of a tkinter entry / input / text field. I use the "ecrire" function with a tk button. When the function uses a substring that is defined outside of it to get the entry current value, it works fine. But when I try to pass the substring as a parameter, the StringVar.get() method returns nothing. Here is the code :

# coding: utf-8

from tkinter import *

fenetre = Tk()
labl = Label(fenetre, text = "Bonjour, monde !")
bouton=Button(fenetre, text="Fermer", command=fenetre.quit)
def ecrire(ligne):
    file = open("save.txt", "a")
    message = ligne.get()
    file.write(message + "\n")
    file.close()

string = StringVar()
entree = Entry(fenetre, textvariable=string, width=10)
btnEcrire = Button(fenetre, text="ecrire", command = ecrire())
labl.pack()
entree.pack()
btnEcrire.pack()
bouton.pack()
fenetre.mainloop()

I'm very new to python and to these libraries, and I'll eventually need to pass StringVars as parameters to that function. What am I doing wrong ?

  • 1
    I believe you want `command = ecrire`, without the parentheses. – John Gordon Mar 19 '23 at 00:34
  • You want `command=lambda: ecrire(string)` – Barmar Mar 19 '23 at 04:09
  • Welcome to Stack Overflow. `Button(fenetre, text="ecrire", command = ecrire())` means "**call `ecrire` now**, and **don't pass it anything**, and make a `Button` that uses **the return value** of that call for the `command`". Please see the linked duplicate for a proper approach to the problem. This is an extremely commonly asked question. – Karl Knechtel Mar 19 '23 at 11:28

1 Answers1

0
...    

btnEcrire = Button(fenetre, text="ecrire", command=lambda: ecrire(string))  

...
len
  • 749
  • 1
  • 8
  • 23
  • Thanks a lot. But why does it work ? Is it linked to the return value of ecrire() ? also sorry for forgetting the parameter in the call for ecrire... – SpaceMansion Mar 19 '23 at 13:10