You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用循环简化Tkinter重复代码批量绘制矩形?

简化重复的Tkinter矩形绘制代码

问题描述

我有一段重复的Tkinter代码,用于绘制一系列鼠标悬停时会变色的矩形。由于矩形数量较多,除两个位置坐标外其余代码完全重复,因此希望用循环简化这段代码。原代码如下:

from tkinter import *

c=Canvas(width=800, height=600, bg="White")

c.create_rectangle(50,50,70,150,outline="Blue",
                   width=2,fill="Gray",activefill="Red")
c.create_rectangle(90,50,110,150,outline="Blue",
                   width=2,fill="Gray",activefill="Red")
c.create_rectangle(130,50,150,150,outline="Blue",
                   width=2,fill="Gray",activefill="Red")
c.create_rectangle(170,50,190,150,outline="Blue",
                   width=2,fill="Gray",activefill="Red")
c.create_rectangle(210,50,230,150,outline="Blue",
                   width=2,fill="Gray",activefill="Red")
c.create_rectangle(250,50,270,150,outline="Blue",
                   width=2,fill="Gray",activefill="Red")
c.create_rectangle(290,50,310,150,outline="Blue",
                   width=2,fill="Gray",activefill="Red")
c.create_rectangle(330,50,350,150,outline="Blue",
                   width=2,fill="Gray",activefill="Red")
c.create_rectangle(370,50,390,150,outline="Blue",
                   width=2,fill="Gray",activefill="Red")
c.create_rectangle(410,50,430,150,outline="Blue",
                   width=2,fill="Gray",activefill="Red")
c.create_rectangle(450,50,470,150,outline="Blue",
                   width=2,fill="Gray",activefill="Red")
c.create_rectangle(490,50,510,150,outline="Blue",
                   width=2,fill="Gray",activefill="Red")
c.pack()
mainloop()

我的初步思路是将矩形初始尺寸设为(x, 50, y, 150),设置x=50、y=70,在x≤490且y≤510时让x每次增加40,但不知道如何将这些整合到循环中。


解决方案

你的思路方向是对的,核心是用循环批量生成坐标。观察原代码的坐标规律:每个矩形左边界x从50开始,每次加40;右边界是左边界加20(50+20=70、90+20=110),所以不需要单独维护y变量,直接用x+20就能得到右边界值。

简化后的代码如下:

from tkinter import *

c = Canvas(width=800, height=600, bg="White")

# 循环生成所有矩形,左边界从50开始,步长40,到490结束(range结束值设为500是因为它是开区间)
for x in range(50, 500, 40):
    c.create_rectangle(x, 50, x + 20, 150, 
                       outline="Blue", width=2, 
                       fill="Gray", activefill="Red")

c.pack()
mainloop()

代码说明

  • range(50, 500, 40)会生成50、90、130…490的序列,刚好对应所有矩形的左边界。
  • 右边界用x+20直接计算,和原代码的坐标逻辑完全一致,省去额外变量的维护。
  • 循环内部复用了原代码的样式参数,最终效果和原代码完全相同,但代码量大幅减少,后续修改样式或调整数量也更方便。

内容的提问来源于stack exchange,提问作者Sarah

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 05:39:54