添加不同的值到使用循环创建的条目。

huangapple go评论62阅读模式
英文:

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=&quot;nw&quot;, 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

huangapple
  • 本文由 发表于 2023年2月16日 03:06:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/75464402.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定