当前位置: 代码迷 >> python >> Python tkinter:如何制作一个形状,使其被对象覆盖而不是轮廓?
  详细解决方案

Python tkinter:如何制作一个形状,使其被对象覆盖而不是轮廓?

热度:80   发布时间:2023-07-16 10:37:19.0

我正在做一个小任务,包括使用尽可能少的对象构建图像。

我已经完成了这个项目,但是我不得不使用一个矩形在四个圆圈后面添加深灰色阴影,而在同一位置使用另一个矩形来绘制轮廓。 有没有一种方法可以使这单个矩形保持原来的样子?

长话短说,我希望变量“ rectangle_back”和“ rectangle_outline”是一个矩形,“ rectangle_back”填充部分被覆盖(现在是这样),“ rectangle_outline”轮廓保持在所覆盖的圆圈上方'rectangle_back'。 能做到吗? 如果是这样,怎么办?

图片:

码:

# File: farmer_john_field
# Author: eluzibur / Elijah Cherry
# Purpose: draw <image>, and calculate area of dark section

from tkinter import *
from tkinter import ttk
import math

def main():
    root = Tk()
    win = Canvas(root, width = 500, height = 500)
    win.grid()

# point a = 200,200
# point b = 300,200
# point c = 300,300
# point d = 200,300

    # rectangle to fill rear area
    rectangle_back = win.create_rectangle (200,200,  300,300, fill="gray")

    # circles will be placed by top left corner and bottom right corner
    circle_a = win.create_oval (200-50, 200-50,   200+50, 200+50, fill="white")
    #                           a  xtl, a  ytl    a  xbr  a  ybr
    circle_b = win.create_oval (300-50, 200-50,   300+50, 200+50, fill="white")
    #                           b  xtl, b  ytl    b  xbr  b  ybr
    circle_c = win.create_oval (300-50, 300-50,   300+50, 300+50, fill="white")
    #                           c  xtl, c  ytl    c  xbr  c  ybr
    circle_d = win.create_oval (200-50, 300-50,   200+50, 300+50, fill="white")
    #                           d  xtl, d  ytl    d  xbr  d  ybr

    # rectangle outline
    rectangle_outline = win.create_rectangle (200,200,  300,300, outline="gray")

    # texts (labels for points a b c d)
    text_a = win.create_text (200,200, anchor="se", text="A", fill="black")
    text_b = win.create_text (300,200, anchor="sw", text="B", fill="black")
    text_c = win.create_text (300,300, anchor="nw", text="C", fill="black")
    text_d = win.create_text (200,300, anchor="ne", text="D", fill="black")

    # collect length information
    length = float(input("Enter length of one side of the square ABCD: "))
    radius = (length/2)
    dark_area_result = math.pi * math.sqrt(radius)
    print ("Area of shaded region =","{:0.2f}".format(dark_area_result))

main()

简短的答案是画布对象属性(轮廓和填充)不能被其他对象单独覆盖。 对象的填充和轮廓是否重叠(模糊)。

管理您的情况通常要做的是创建一个包含两个矩形的矩形类。

class Rectangle:
    def __init__(self, canvas, x0, y0, x1, y1):
        self.back = canvas.create_rectangle (x0, y0, x1, y1, fill="gray")
        self.outline = canvas.create_rectangle (x0, y0, x1, y1, outline="gray")

...
rectangle = Rectangle(win, 200,200, 300,300)

然后定义一种检查Rectangle对象的交集的方法,以确定是否在其他窗口小部件上方引发outline属性。