"""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()
标签:Canvas,randint,代码,random,master,root,self
From: https://www.cnblogs.com/aihonghua/p/18165715