Adding different values to the entries created with the loop
Question:
For example, I want to insert the numbers from 1 to 10, respectively, from the beginning to the end, into the 10 entries I created with a loop.
from tkinter import *
root = Tk()
root.title("")
root.geometry("500x400")
canva = Canvas(root,width=450,height=350,highlightbackground="black")
for i in range(40, 240, 21):
Abent = Entry(root, width=10)
Abentry = canva.create_window(50, i, anchor="nw", window=Abent)
Abent.insert(0,1)
canva.pack()
root.mainloop()
Answers:
You can do this by using enumerate on your for
loop’s iterable
for index, y_pos in enumerate(range(40, 240, 21)): # enumerate over range
abent = Entry(root, width=10)
abentry = canva.create_window(50, y_pos, anchor="nw", window=abent)
abent.insert(0, index)
Also: to be compliant with PEP8, I’ve renamed your variables to use lowercase names! For future reference, Uppercase Names are reserved for classes like Entry
For example, I want to insert the numbers from 1 to 10, respectively, from the beginning to the end, into the 10 entries I created with a loop.
from tkinter import *
root = Tk()
root.title("")
root.geometry("500x400")
canva = Canvas(root,width=450,height=350,highlightbackground="black")
for i in range(40, 240, 21):
Abent = Entry(root, width=10)
Abentry = canva.create_window(50, i, anchor="nw", window=Abent)
Abent.insert(0,1)
canva.pack()
root.mainloop()
You can do this by using enumerate on your for
loop’s iterable
for index, y_pos in enumerate(range(40, 240, 21)): # enumerate over range
abent = Entry(root, width=10)
abentry = canva.create_window(50, y_pos, anchor="nw", window=abent)
abent.insert(0, index)
Also: to be compliant with PEP8, I’ve renamed your variables to use lowercase names! For future reference, Uppercase Names are reserved for classes like Entry