Tkinter 矩形

Salman Mehmood 2024年2月15日
  1. 在 Tkinter 中使用 canvas 方法创建一个基本的矩形示例
  2. Tkinter 矩形选项
Tkinter 矩形

这个演示将展示如何使用 Tkinter 中的 canvas 方法创建一个矩形。

在 Tkinter 中使用 canvas 方法创建一个基本的矩形示例

每个矩形在左上角定义为 (x1, y1),在右下角像素区域定义为 (x2, y2)。

例如,矩形左上角(100,100)和右下角(102,102)是两个像素乘两个像素的正方形,包括像素(101,101)但不包括(102,102)。画布可用于创建多种形状。

from tkinter import *

# Initialize a window
root = Tk()
root.geometry("350x250")
# Create an instance of a canvas
_canvas = Canvas(root, height=200, width=200)
_canvas.pack()
# create rectangle
_canvas.create_rectangle(50, 50, 180, 120, outline="black", fill="blue")
root.mainloop()

矩形的基本示例

Python Tkinter Canvas 具有用于创建对象或形状的内置方法。我们将使用 create_rectangle() 方法来创建一个矩形。

create_rectangle() 方法接受四个点 x1, y1, x2, y2。这里 x1 和 y1 是左上角,x2 和 y2 是右下角。

Tkinter 矩形选项

dash 此选项是整数元组。第一个数字有助于创建将要绘制的像素。第二个数字有助于在我们再次开始绘制之前跳过将被跳过的像素,依此类推。当元组中的所有数字都完成后,它们将被类似地重复使用,直到边界结束。
# create dashed border
_canvas.create_rectangle(50, 50, 180, 120, outline="black", fill="blue", dash=(4, 6))

现在我们可以看到在跳过 6 个像素后由 4 个像素创建边界线的位置。

创建虚线边框

state 默认情况下,创建矩形时,state 选项值为 NORMAL。如果使用 activefill 选项设置条件,则当鼠标悬停在矩形上时,这将是活动的。我们可以使用 state=DISABLED 禁用状态。
_canvas.create_rectangle(50, 50, 180, 120, activefill="blue")

主动填充

_canvas.create_rectangle(50, 50, 180, 120, state=DISABLED, activefill="blue")

状态禁用

stipple stipple 选项有助于点画矩形。默认情况下,在 stipple = ''中,表示纯色。标准值可以是 stipple = 'gray25'。除非将填充设置为特定颜色,否则它没有效果。你可以在其中放置几个​​值:'gray50''gray25''error''gray75''gray12''hourglass''info' , 'questhead', 'question', 和 'warning'
# Create a pattern
_canvas.create_rectangle(50, 50, 180, 120, stipple="gray25", fill="black", outline="")

tkinter stipple

我们可以使用 width 选项增加宽度。

_canvas.create_rectangle(10, 10, 150, 100, fill="blue", width=5)

create_rectangle() 方法中有几个选项。

作者: Salman Mehmood
Salman Mehmood avatar Salman Mehmood avatar

Hello! I am Salman Bin Mehmood(Baum), a software developer and I help organizations, address complex problems. My expertise lies within back-end, data science and machine learning. I am a lifelong learner, currently working on metaverse, and enrolled in a course building an AI application with python. I love solving problems and developing bug-free software for people. I write content related to python and hot Technologies.

LinkedIn