0

Can someone please help me understand why my while loop is not printing what I intend?

My code creates a tkinter window with a specified number of labels. It should then create the same amount of entry boxes. It does both of these.

If I print the part_number variable it prints as intended: "Part 1", "Part 2", "Part 3". etc.

If I print the entry variable it returns: ".!entry", ".!entry1", ".!entry2", etc where it should print "part_entry1", "part_entry2", "part_entry3". etc.

Thanks for the help.

from tkinter import *

main = Tk()
main.title('Job Logger')
main.geometry("850x750")

'''''''''
def submit():
    a = part_entry1.get()
    #b = part_entry2.get()
    #c = part_entry3.get()

    print(a)
    #print(b)
    #print(c)
'''

count = 0
x = 50
y = 30
x2 = 150
while count < 3:
    part_number = ('Part ' + (str(count + 1)))
    Label(main, text=part_number).place(x = x, y = y)
    entry = ('part_entry' + (str(count + 1)))
    entry = Entry(main)
    entry.place(width=120, x=x2, y=y)
    y += 30
    count += 1
    print(part_number)
    print(entry)

'''''''''
Button(main, text="Submit Run info", command=submit).place(width=100, x=375, y=200)
'''

mainloop()

Prometheus
  • 45
  • 5
  • 3
    First, you bind `entry` to a string. Then, on the next line, you immediately discard that string and rebind `entry` to a `tkinter.Entry` widget object. – Paul M. Jul 09 '21 at 19:14
  • Is that what I am doing or I need to do? – Prometheus Jul 09 '21 at 19:21
  • 1
    That's what you're doing - and it's incorrect. – Paul M. Jul 09 '21 at 19:22
  • Could you elaborate on what I should be doing? – Prometheus Jul 09 '21 at 19:23
  • use different names for variables - ie. `entry_text = 'part_entry' + (str(count + 1))` and `entry = Entry(...)` and later `print(entry_text)` . But this way you can't create variable `part_entry_1`, etc. And you shouldn't do this but you should keep it on list and use index to acces object on list. – furas Jul 09 '21 at 20:09

1 Answers1

2

The main problem is you're trying to dynamically create variables (and doing it wrong), however that's almost always a poor idea (see How do I create variable variables?). I suggest you put the Entry widgets in a list and refer to it in your callback function. Here's what I mean:

from tkinter import *

main = Tk()
main.title('BTD Job Logger')
main.geometry("850x750")

def submit():
    for i, entry in enumerate(part_entries, start=1):
        print(f'part entry {i}: {entry.get()!r}')

NUM_PARTS = 3
x = 50
y = 30
x2 = 150

part_entries = []  # List of Entry widgets.
for i in range(NUM_PARTS):
    part_number = 'Part ' + str(i + 1)
    Label(main, text=part_number).place(x=x, y=y)
    entry = Entry(main)
    part_entries.append(entry)
    entry.place(width=120, x=x2, y=y)
    y += 30

Button(main, text="Submit Run info", command=submit).place(width=100, x=375, y=200)

mainloop()
martineau
  • 119,623
  • 25
  • 170
  • 301