我在 python 和 tkinter 上创建了可以构建绘图的程序。但我不能同时建造多个地块。请帮我。解释我如何实现它。
from tkinter import *
import math
wind = Tk()
wind.geometry("400x400")
canw = Canvas(wind, width=400, height=400)
canw.pack()
canw.place(x=-1, y=-1)
lines_index = 0
numbers = -8
#create cages(like in notebook) [one cage = 10x10 px]
while lines_index <= 40:
if lines_index == 20:
canw.create_line(0, 0+10*lines_index, 400, 0+10*lines_index, fill="#000", width=2) #x_line
canw.create_line(10*lines_index, 0, 10*lines_index, 400, fill="#000", width=2) #y_line
else:
canw.create_line(0, 0+10*lines_index, 400, 0+10*lines_index, fill="#4C8098") #x_line
canw.create_line(10*lines_index, 0, 10*lines_index, 400, fill="#4C8098") #y_line
lines_index = lines_index + 1
numbers = numbers + 1
print(lines_index, numbers)
# b = [-16,-15,-14,-13,-12,-11,-10,-9,-8,-7,-6,-5,-4,-3,-2,-1,
# 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16] #test properties
# fun_index = 1 #don`t use now
b = [] #array for properties
i = -20
while i <= 20:
b.append(i)
i= i + 0.01 #change accuracy
print(i)
for x in b: #loop create points for plot
y = x**2
# y = (6*(x**2))+(2*x)+8
# y = (6*(x**2))+8
# y= 3*(x+3)
# y = 3**x
# y=x**3
# y = x**(1/2) #not work
# y = 1/x
canw.create_oval((x*10)+200, -(y*10)+200, (x*10)+200, -(y*10)+200, outline='red', fill="red")
print(y)
wind.mainloop()
我尝试在循环中使用 if else(为绘图创建点),但这不是一个好主意。因为所有点都分为所有数量的地块。
首先,请注意
create_oval
方法绘制椭圆(或在满足适当半径条件的特殊情况下绘制圆),并且它具有类似 x0, y0, x1, y1
的输入,其中:
“椭圆适合由左上角坐标
(x0, y0)
和右下角外侧点的坐标 (x1, y1)
定义的矩形。”。
来源:https://anzeljg.github.io/rin2/book2/2405/docs/tkinter/create_oval.html
其次,你的坐标系有点偏离。在弹出的图中,您的原点
(0,0)
实际上位于图的左上角。您可以通过执行类似 canw.create_oval(50, 50, 20, 20, outline='red', fill="red")
之类的操作来验证这一点,并看到该圆实际上靠近绘图窗口的左上角,而不是靠近您似乎用两条主黑线定义的原点。因此,在您共享的代码的 for x in b:
循环中,您在同一画布上绘制多个椭圆的努力是徒劳的,因为这些椭圆远远超出了可见区域。
解决方案是移动坐标系的原点以精确地适应所需的 (0,0),即两条黑线相交的位置。您可以通过包含值
200
: 的偏移量来实现此目的
canw.create_oval(x1+200, -y1+200, x2+200, -y2+200, outline='red', fill="red")
不过,这里还有一个重要的点需要大家注意。
(x0,y0)
和 (x1,y1)
不是(分别)椭圆所拟合的矩形的左上角和右下角,而是在原点移动之后,(x0,y0)
变成了左下,并且(x1,y1)
成为矩形的右上角 角。
考虑到这些,您可以在
for
循环中绘制任何您想要的内容。由于我不明白你在(数学上)试图绘制什么,所以我不能在这里给你一个测试用例,但如果你可以向我提供任何特殊情况,我可以通过更新我的答案来进一步提供帮助。