我正在进行一项小型任务,包括使用尽可能少的对象构建图像。
我已经完成了这个项目,但是我不得不使用一个矩形在四个圆圈后面给出深灰色阴影,在同一个地方使用另一个矩形只是为了它的轮廓。有没有办法制作这个单一的矩形,同时保留它现在的样子?
长话短说,我希望变量'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()
答案 0 :(得分:0)
简短的回答是画布对象属性(轮廓和填充)不能与其他对象分开重叠。对象的填充和轮廓重叠(隐藏)或不重叠。
管理你的情况经常做的是创建一个包含两个矩形的矩形类。
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属性提升到其他小部件之上。