Google News
logo
Computer Graphics - Interview Questions
Do you know how to create graphics in Python using the Tkinter module?
Yes, I can guide you through creating graphics in Python using the Tkinter module. Tkinter is a standard GUI (Graphical User Interface) library for Python that provides tools for creating windows, buttons, text boxes, and other GUI elements, including simple graphics.

Here's a basic example of how to create a simple graphical application using Tkinter to draw shapes:
import tkinter as tk

# Create a window
root = tk.Tk()
root.title("Simple Graphics")

# Create a canvas widget
canvas = tk.Canvas(root, width=400, height=400)
canvas.pack()

# Draw a rectangle
rectangle = canvas.create_rectangle(50, 50, 150, 150, fill="blue")

# Draw an oval
oval = canvas.create_oval(200, 50, 300, 150, fill="red")

# Draw a line
line = canvas.create_line(50, 200, 150, 300, fill="green")

# Draw text
text = canvas.create_text(200, 200, text="Hello, Tkinter!", fill="black")

# Function to change the color of the rectangle
def change_color():
    canvas.itemconfig(rectangle, fill="orange")

# Button to change the color of the rectangle
button = tk.Button(root, text="Change Color", command=change_color)
button.pack()

# Run the Tkinter event loop
root.mainloop()?
In this example :

* We import the Tkinter module and create a window (root) with the Tk() constructor.

* We create a canvas widget (canvas) inside the window to draw graphics.

* We draw a rectangle, an oval, a line, and text on the canvas using various create_* methods.

* We define a function (change_color) to change the color of the rectangle when a button is clicked.

* We create a button (button) to trigger the color change when clicked.

* Finally, we start the Tkinter event loop with mainloop() to display the window and handle user interactions.
Advertisement