gpt4 book ai didi

python-3.x - 遍历列表并通过 create_text 输出

转载 作者:行者123 更新时间:2023-12-03 08:28:40 27 4
gpt4 key购买 nike

我在使用 tkinter 的 create_text 时遇到了一些问题。我正在尝试遍历列表并让 create_text 逐一输出列表中的每一项。我无法弄清楚,因为每次我尝试过,它都不会按照我想要的方式工作。这里有一些代码可以说明这个问题:

class GUI(Frame):
def __init__(self, master):
self.test_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
self.c = Canvas(master, width=300, height=300)
self.c.pack()

for items in self.test_list:
items = items

for i in range(0, 300, 100):
for j in range(0, 300, 100):
self.c.create_text(j + 25, i + 20, text=items)

root = Tk()
root.title("Test")
root.geometry("300x300")
GUI(root)
mainloop()

谢谢你,感谢你的帮助。

最佳答案

您的代码有严重的缩进问题。
此外,您没有在任何对象上调用 mainloop
然后,对象在 Canvas 上的位置在可见窗口之外:

我修改了代码,让它运行,并在 Canvas 上显示一些东西;从那里,您可以修改它以满足您的需要。

import tkinter as tk


class GUI(tk.Frame):
def __init__(self, master):
self.test_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
self.c = tk.Canvas(master, width=300, height=300)
self.c.pack()

for idx, elt in enumerate(self.test_list):
row = (idx // 3 + 5) * 20
col = (idx % 3 + 5) * 20

self.c.create_text(row, col, text=elt)


if __name__ == '__main__':

root = tk.Tk()
root.title("Test")
root.geometry("300x300")
GUI(root)
root.mainloop()

关于python-3.x - 遍历列表并通过 create_text 输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50166235/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com