首页 > 解决方案 > 如何在此代码中制作对角线?

问题描述

最终产品应如下所示在此处输入图像描述

如何在图像的下部制作三角形?到目前为止,我只得到了 6 条条纹。我正在使用 tkinter 和随机。

import tkinter
import random
import math
import time

canvas = tkinter.Canvas(width=600 ,height=400)
canvas.pack()
previerka = tkinter.Tk()
frame = tkinter.Frame(previerka)
frame.pack()

def shooting1():
    for a in range(8000):
        y = 0
        x = 0
        xr = random.randint(0,600)
        yp = random.randint(0,600)
        if yp <= 600:
            canvas.create_oval(x+xr,y+yp,x+xr,y+yp, outline="yellow", width=2)
        if 100 <= xr <= 300:
            canvas.create_oval(x+xr,y+yp,x+xr,y+yp, outline="black", width=2)
        if 200 <= xr <= 400:
            canvas.create_oval(x+xr,y+yp,x+xr,y+yp, outline="blue", width=2)
        if 300 <= xr <= 500:
            canvas.create_oval(x+xr,y+yp,x+xr,y+yp, outline="green", width=2)
        if 400 <= xr <= 600:
            canvas.create_oval(x+xr,y+yp,x+xr,y+yp, outline="white", width=2)
        if 500 <= xr <= 700:
            canvas.create_oval(x+xr,y+yp,x+xr,y+yp, outline="red", width=2)
button1=tkinter.Button(frame, text="shooting", fg="black", bg="white", command=shooting1)
button1.pack()

标签: pythontkinter

解决方案


我不知道你是否意识到这一点,但你正在重叠所有颜色点(尝试将任何椭圆的宽度更改为 3 或 4,你会意识到这一点)。您需要根据该行计算 x 和 y 值是否兼容y = 2x/3(对于计算机,y 轴是倒置的,所以y = 400 - 2x/3)。然后,只有这样,您才会在该画布上绘图。这是一个例子。

import tkinter
import random

previerka = tkinter.Tk()
canvas = tkinter.Canvas(previerka, width=600, height=400)
canvas.pack()
frame = tkinter.Frame(previerka)
frame.pack()

def shooting1():
    y = 0
    x = 0
    i = 0
    r  =("%02x"%random.randint(0,255))
    g = ("%02x"%random.randint(0,255))
    b = ("%02x"%random.randint(0,255))
    rand_color="#"+r+g+b

    for _ in range(20000):
        xr = random.randint(0,600)
        yp = random.randint(0,400)
        if yp<=400-2*xr//3:
            if xr < 100:
                canvas.create_oval(x+xr,y+yp,x+xr,y+yp, outline="yellow", width=2)
            elif xr < 200:
                canvas.create_oval(x+xr,y+yp,x+xr,y+yp, outline="black", width=2)
            elif xr < 300:
                canvas.create_oval(x+xr,y+yp,x+xr,y+yp, outline="blue", width=2)
            elif xr < 400:
                canvas.create_oval(x+xr,y+yp,x+xr,y+yp, outline="green", width=2)
            elif xr < 500:
                canvas.create_oval(x+xr,y+yp,x+xr,y+yp, outline="white", width=2)
            elif xr <= 600:
                canvas.create_oval(x+xr,y+yp,x+xr,y+yp, outline="red", width=2)
        else:
            canvas.create_oval(x+xr,y+yp,x+xr,y+yp, outline=rand_color, width=2)

button1=tkinter.Button(frame, text="shooting", fg="black", bg="white", command=shooting1)
button1.pack()
previerka.mainloop()

在此处输入图像描述


推荐阅读