📜  tkinter triangle - Python (1)

📅  最后修改于: 2023-12-03 15:05:36.059000             🧑  作者: Mango

Tkinter Triangle - Python

Tkinter is a popular Python library for creating graphical user interfaces. It provides a wide variety of widgets for building interactive applications. In this article, we will explore how to create a triangle using Tkinter.

Creating a Triangle

To create a triangle in Tkinter, we need to use the Canvas widget. The Canvas widget provides a drawing surface for creating shapes like lines, rectangles, circles, and polygons. To make a triangle, we need to create a polygon with three points.

import tkinter as tk

root = tk.Tk()

canvas = tk.Canvas(root, width=300, height=200)
canvas.pack()

points = [150, 50, 50, 150, 250, 150]
canvas.create_polygon(points, fill='blue')

root.mainloop()

In this code snippet, we first import the tkinter module and create an instance of the Tk class. We then create a Canvas widget with a width of 300 pixels and a height of 200 pixels, and pack it into the main window. Next, we define the three points of the triangle as a list [150, 50, 50, 150, 250, 150]. These points represent the x and y coordinates of the three vertices of the triangle. Finally, we create a polygon on the canvas using create_polygon() method and passing the points list as the argument. We also set the fill attribute to blue to fill the triangle with color.

Conclusion

In this article, we learned how to create a triangle using Tkinter. We used the Canvas widget to create a polygon with three points, representing the vertices of the triangle. After that, we used create_polygon() method to create the triangle on the canvas. With these basic skills, you can create many more shapes using Tkinter.