0

I'm new to Tkinter, and also new to this forum. I am trying to learn to use Tkinter, and I have a problem!

I want to save some text to a text file by writing the text and then press a button to run a function that saves the info. But it seems like my "command" does not start the function.

def ny_artikel():
   artikel_data = open ("artikel_databas.txt", "w")
   artikel_data.write(ny_artikel.get())
   artikel_data.close ()

spara_artikel = Button(new_product_window, text ="Save new article", command = ny_artikel)
spara_artikel.grid(row=7, column=1)

ny_artikel is an entry box used in my program, but I think it's too many rows to paste it all in here.

When I press the button, nothing at all happens. Not even an error message.

nbro
  • 15,395
  • 32
  • 113
  • 196
  • 2
    Are you sure there's no error message? The way you've defined a function `ny_artikel` and presumably expect there to be an `Entry` widget somewhere with the exact same name, I'd be surprised if there was no error anywhere. – TigerhawkT3 Mar 14 '17 at 17:45
  • 1
    Put `print('function called')` in a function (at the top) to determine whether the function is called. – Terry Jan Reedy Mar 14 '17 at 17:54
  • I tried to do as you are saying Terry. I typed print(ny_artikel). When i did I did not get any error message, but a blue text saying: Is that a sign that there are something wrong or just a confirmation that the finction are running? Is there a problem that I call this function "ny_artikel" from another function? Thanks for your kind help :) – Jonas Rydholm Mar 14 '17 at 20:27

1 Answers1

0

I assume, that the code in your answer is only part of your python file. I tried it out with Entry e in my example and it works right:

import tkinter

def ny_artikel():
   with open('artikel_databas.txt', 'w') as artikel_data:
      artikel_data.write(e.get())

main = tkinter.Tk()
e = tkinter.Entry(main)
e.grid(row=0, column=0)
spara_artikel = tkinter.Button(main, text ="Save new article", command = ny_artikel)
spara_artikel.grid(row=1, column=0)
main.mainloop()

As alternative I used 'with' 'as' in ny_artikel() function, which automatically closes the file. Using file.close() works fine as well.

What is the python keyword "with" used for?

Community
  • 1
  • 1