Skip to content
Advertisement

Tkinter function creates variable that can’t be added to list with .get() from entry

First off, I am aware that there are many questions out there with .get() not properly working and I have read through many of them. My issue is that my program has a button that every time it is pressed, it adds a new entry box for a new Player to be added, then I then want to create a Player object (I have the player class defined in another file) and add the Player object to a list. Here is the function for the “Add Player” button:

JavaScript

(team_wind is the window because it is creating a Team of Players. the Team class is also defined in another file) After some reaserch, I realized that mainloop would terminate that block of code (as far as my understanding). So, when I run the program, the entry returns ”. I know this is a very common issue, but it is wierd for mine because I can’t figure out a way to get around it. I already have a working part of the tkinter window for a single player with a single entry box, so I know how .get() works. I’ve tried using .update() and .update_idletasks().

  • I have tried moving the player_list.append to before the mainloop because I know the code after is unreachable, but if I move it to before, then it returns nothing

. If I try to do it in another function or after the code terminates, then it won’t work because if the button is pressed multiple times, each entry will have the same variable name. I think this means it has to be done in this function, but not sure how to do that with mainloop. Here is the code to create the window so it will run. All I need is for it to be able to print or return the list with the player objects for however many players there are (depends how many times the button is pressed). I have provided the code needed to run the program and cut out everything else that would cause errors. Thanks

JavaScript

Advertisement

Answer

You should have only one mainloop() – in main().

You could use your list to keep widgets Entry – without using .get() – and you should use .get() when you print list.


Minimal working code.

I used Frame to keep Label and Entry and this way it adds Entry before Buttons.

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement