Drawing basic shapes in python 2 [closed]

2019-08-29 12:17发布

问题:

How would I draw a simple partially transparent rectangle in python. I would like to not download anything from the internet and purely use python 2.7.3. I would like to also control where the rectangle starts and ends and control its width and height. The end goal of this is to have a map (of michigan and its great lakes) and have color coded rectangles pop up along the coast to visually show what the expected weather will be like based of buoys data from the NDBV. So in short, a map that i can place color coded rectangles on, that will be oriented along the coast of western michigan.

回答1:

Here is some Tkinter sample code. Note that, so far as I am aware, Tkinter does not support transparency; but it can fake it by stippling, as demonstrated here:

# copied from http://www.kosbie.net/cmu/fall-10/15-110/koz/misc-demos/src/semi-transparent-stipple-demo.py

# semi-transparent-stipple-demo.py
# note: stipple only works for some objects (like rectangles)
# and not others (like ovals).  But it's better than nothing...

from Tkinter import *

def redrawAll(canvas):
    canvas.delete(ALL)
    # draw a red rectangle on the left half
    canvas.create_rectangle(0, 0, 250, 600, fill="red")
    # draw semi-transparent rectangles in the middle
    canvas.create_rectangle(200,  75, 300, 125, fill="blue", stipple="")
    canvas.create_rectangle(200, 175, 300, 225, fill="blue", stipple="gray75")
    canvas.create_rectangle(200, 275, 300, 325, fill="blue", stipple="gray50")
    canvas.create_rectangle(200, 375, 300, 425, fill="blue", stipple="gray25")
    canvas.create_rectangle(200, 475, 300, 525, fill="blue", stipple="gray12")

def init(canvas):
    redrawAll(canvas)

########### copy-paste below here ###########

def run():
    # create the root and the canvas
    root = Tk()
    canvas = Canvas(root, width=500, height=600)
    canvas.pack()
    # Store canvas in root and in canvas itself for callbacks
    root.canvas = canvas.canvas = canvas
    # Set up canvas data and call init
    canvas.data = { }
    init(canvas)
    # set up events
    # root.bind("<Button-1>", mousePressed)
    # root.bind("<Key>", keyPressed)
    # timerFired(canvas)
    # and launch the app
    root.mainloop()  # This call BLOCKS (so your program waits until you close the window!)

run()

which produces something like



回答2:

Check out

svgfig or svgwrite for svg

reportlab for pdf

pyglet for drawing to a window