pythontkinter:如何制作一个填充被对象覆盖而不是轮廓的形状?

2024-09-27 23:28:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在做一个小任务,包括用尽可能少的物体建立一个图像。在

我有这个项目完成,但我不得不用一个矩形给它四个圆圈后面的深灰色阴影,另一个矩形在同一个地方只是为了它的轮廓。有没有一种方法可以使这一个矩形保持现在的样子?在

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

图片:enter image description here

代码:

# 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()

Tags: oftextcreatebackareafillwinpoint
1条回答
网友
1楼 · 发布于 2024-09-27 23:28:03

简而言之,画布对象属性(outline和fill)不能被其他对象单独重叠。对象的填充和轮廓重叠(模糊)或不重叠。在

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

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)

然后定义一个方法来检查矩形对象的交集,以确定是否将outline属性提升到其他小部件之上。在

相关问题 更多 >

    热门问题