2

How would I accomplish the following HTML5 canvas stroke using Python? Would I use Tkinter? Qt? WxWidgets? Some other library?

<!DOCTYPE html>
<html>
<body>

<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
</canvas>

<script>

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.moveTo(20,20);
ctx.lineTo(20,100);
ctx.lineTo(70,100);
ctx.strokeStyle="red";
ctx.stroke();

</script> 

</body>
</html>

1 Answer 1

2

With tkinter use can use the Canvas widget type. You can't directly change the color of the border; I'm not sure if that's part of the question or not. You can easily draw a colored border, or put it inside a colored frame to give it a border.

To create the line, use the create_line method.

Here's an example:

import Tkinter as tk

class Example(tk.Frame):
    def __init__(self, root):
        tk.Frame.__init__(self, root)
        self.canvas = tk.Canvas(width=300, height=150,borderwidth=1)
        self.canvas.pack(side="top", fill="both", expand=True)
        points = (20,20,20,100,70,100)
        self.canvas.create_line(points, fill="red")

if __name__ == "__main__":
    root = tk.Tk()
    Example(root).pack(fill="both", expand=True)
    root.mainloop()
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you! No, the border color is irrelevant, but that's useful information.
This is a totally separate question, but can the canvas be saved as SVG?
@MarkRichman: there is no built-in support for svg, but the objects on the canvas are objects rather than pixmaps, and the canvas has good introspection capabilities. It should be pretty straight-forward to convert the contents of the canvas to SVG. I've seen it done in Tcl (eg: wiki.tcl.tk/4534), but I haven't seen it done in python.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.