2025年3月7日 星期五

python tkinter canvas sample



import tkinter as tk
import random

def change_color():
    """隨機改變矩形顏色"""
    colors = ["red", "blue", "green", "purple", "orange"]
    new_color = random.choice(colors)
    canvas.itemconfig(rect, fill=new_color)

def draw_point(event):
    """在點擊的位置畫一個小圓點"""
    x, y = event.x, event.y  # 獲取滑鼠點擊的位置
    colors = ["black", "red", "blue", "green", "purple"]
    color = random.choice(colors)  # 隨機顏色
    r = 3  # 點的半徑
    canvas.create_oval(x-r, y-r, x+r, y+r, fill=color, outline=color)

# 建立主視窗
root = tk.Tk()
root.title("Canvas 畫布")

# 建立 Canvas
canvas = tk.Canvas(root, width=400, height=300, bg="white")
canvas.pack()

# **繪製圖形**
# 畫一條線
canvas.create_line(50, 50, 350, 150, fill="red", width=3)

# 畫一個矩形(可點擊變色)
rect = canvas.create_rectangle(50, 50, 150, 150, outline="blue", width=2, fill="lightblue")

# 畫一個圓形(橢圓)
canvas.create_oval(180, 50, 250, 120, outline="green", width=2)

# 畫一個多邊形(三角形)
canvas.create_polygon(200, 200, 300, 200, 250, 100, outline="purple", fill="yellow", width=2)

# 畫文字
canvas.create_text(200, 250, text="Hello, Tkinter! 視窗工具", font=("Arial", 16), fill="black")

# **點擊矩形改變顏色**
canvas.tag_bind(rect, "<Button-1>", lambda event: change_color())

# **點擊畫布時,繪製小圓點**
canvas.bind("<Button-1>", draw_point)

# 啟動主迴圈
root.mainloop()


沒有留言:

張貼留言