英文:
Adding different values to the entries created with the loop
问题
例如,我想要使用循环从1到10依次将数字插入到我创建的10个条目中,从开始到结束。
from tkinter import *
root = Tk()
root.title("")
root.geometry("500x400")
canvas = Canvas(root, width=450, height=350, highlightbackground="black")
for i in range(40, 240, 21):
entry = Entry(root, width=10)
entry_window = canvas.create_window(50, i, anchor="nw", window=entry)
entry.insert(0, 1)
canvas.pack()
root.mainloop()
<details>
<summary>英文:</summary>
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()
</details>
# 答案1
**得分**: 1
你可以通过在你的`for`循环的可迭代对象上使用[enumerate](https://docs.python.org/3/library/functions.html?#enumerate)来完成这个操作。
```python
for index, y_pos in enumerate(range(40, 240, 21)): # 在范围上使用enumerate
abent = Entry(root, width=10)
abentry = canva.create_window(50, y_pos, anchor="nw", window=abent)
abent.insert(0, index)
另外,为了符合PEP8的规范,我已经将你的变量重命名为小写名称!供以后参考,大写名称通常用于类,如Entry
。
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论