dragov 发表于 2025-2-24 16:49:43

Tkinter _ 使用 for 语句替代 ?



能否使用for循环语句替代吗   ?

from tkinter import *
root=Tk()
def jksf(a):
      lxw=Canvas(root,width=874,height=839,background=a)
      lxw.pack(expand=True)
      lxw.create_rectangle(50,50,100,100,fill="fuchsia")
      lxw.create_rectangle(100,100,200,200,fill="sienna")
      lxw.create_rectangle(200,200,350,350,fill="burlywood")
      lxw.create_rectangle(350,350,550,550,fill="linen")
      lxw.create_rectangle(550,550,800,800,fill="coral")
jksf("lavender")
mainloop()

FishC 发表于 2025-2-24 16:56:32

当然可以使用 for 循环 语句来替代重复的 create_rectangle 调用。下面是替换后的代码:


from tkinter import *

root = Tk()

def jksf(a):
    lxw = Canvas(root, width=874, height=839, background=a)
    lxw.pack(expand=True)
   
    rectangles = [
      (50, 50, 100, 100, "fuchsia"),
      (100, 100, 200, 200, "sienna"),
      (200, 200, 350, 350, "burlywood"),
      (350, 350, 550, 550, "linen"),
      (550, 550, 800, 800, "coral")
    ]
   
    for x1, y1, x2, y2, color in rectangles:
      lxw.create_rectangle(x1, y1, x2, y2, fill=color)

jksf("lavender")
mainloop()


这样,我们使用了一个包含每个矩形属性的列表,并使用 for 循环 来简化代码。

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。

很cool的阳 发表于 2025-2-24 17:25:32

from tkinter import *

root = Tk()

def jksf(a):
    lxw = Canvas(root, width=874, height=839, background=a)
    lxw.pack(expand=True)
   
    # 定义矩形的起始坐标、宽高和颜色
    rectangles = [
      (50, 50, 100, 100, "fuchsia"),
      (100, 100, 200, 200, "sienna"),
      (200, 200, 350, 350, "burlywood"),
      (350, 350, 550, 550, "linen"),
      (550, 550, 800, 800, "coral")
    ]
   
    # 使用 for 循环绘制矩形
    for rect in rectangles:
      lxw.create_rectangle(rect, rect, rect, rect, fill=rect)

jksf("lavender")
mainloop()
页: [1]
查看完整版本: Tkinter _ 使用 for 语句替代 ?