程式碼8

thanksDay發表於2024-04-29
"""canvas畫布"""
from tkinter import *
import random

class Application(Frame):
    def __init__(self, master=None):
        super().__init__(master)
        self.master = master
        self.pack()
        self.create_widgets()

    def create_widgets(self):
        # 建立Canvas元件,設定寬度和高度
        self.canvas = Canvas(self, width=400, height=300, bg="white")
        self.canvas.pack()

        # 在Canvas上繪製隨機顏色的矩形
        for _ in range(10):
            # 隨機生成矩形的座標和大小
            x1, y1 = random.randint(50, 350), random.randint(50, 250)
            x2, y2 = x1 + random.randint(20, 50), y1 + random.randint(20, 50)
            # 隨機生成填充色
            color = "#{:06x}".format(random.randint(0, 0xFFFFFF))
            # 使用create_rectangle方法在Canvas上繪製矩形
            self.canvas.create_rectangle(x1, y1, x2, y2, fill=color)

# 建立主視窗
root = Tk()
root.geometry("400x300+300+300")  # 設定視窗大小和位置
root.title("Canvas畫布")  # 設定視窗標題

# 建立Application例項並關聯到主視窗
app = Application(master=root)

# 開啟主事件迴圈
root.mainloop()

相關文章