Advertisement
jimkilled

GRAPHICS V5 main.py

Dec 16th, 2020
452
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 10.12 KB | None | 0 0
  1. from tkinter import *
  2. from tkinter import ttk
  3. from graphics import *
  4. from math import *
  5.  
  6.  
  7. def initialize_window(window, title, size=(1024, 720), sizable=(False, False)):
  8.     '''
  9.    Устанавливает заголовок окна, размеры по осям X, Y и устанавливает возможность изменения по осям X, Y
  10.    args - window (Tk), title (str), size (tuple(int, int)), sizable (tuple(bool, bool))
  11.    return - None
  12.    '''
  13.     window.title(title)
  14.     window.geometry(f'{size[0]}x{size[1]}')
  15.     window.resizable(sizable[0], sizable[1])
  16.  
  17.  
  18. def initialize_widgets(window, start, size=(1024, 720)):
  19.     global canvas
  20.     canvas = Canvas(window, bg='#fff', width=size[0], height=size[1])
  21.     canvas.place(x=start[0], y=start[1])
  22.  
  23.     text = Label(window, text='y = ', font=('Arial', 13, 'bold'))
  24.     text.place(x=1130, y=347)
  25.  
  26.     global ent_func
  27.     ent_func = Entry(window, width='20')
  28.     ent_func.place(x=1168, y=350)
  29.  
  30.     but_func = Button(window, text='Сгенерировать', command=get_and_draw_graphic)
  31.     but_func.place(x=1175, y=374)
  32.  
  33.     but_erase_last_func = Button(window, text='Стереть', command=erase_graphic)
  34.     but_erase_last_func.place(x=1175, y=400)
  35.  
  36.     but_erase_all = Button(window, text='Стереть всё', command=erase_graphics)
  37.     but_erase_all.place(x=1175, y=426)
  38.  
  39.     but_hide_graph = Button(window, text='Скрыть', command=hideshow_graphic)
  40.     but_hide_graph.place(x=1175, y=452)
  41.  
  42.     text = Label(window, text='y =', font=('Arial', 13, 'bold'))
  43.     text.place(x=115, y=748)
  44.  
  45.     global func_listbox
  46.     func_listbox = Listbox(window, width=30, height=20, selectmode=EXTENDED)
  47.     func_listbox.place(x=1145, y=20)
  48.  
  49.     scroll = Scrollbar(window, command=func_listbox.yview, orient=VERTICAL)
  50.     scroll.place(x=1329, y=20)
  51.  
  52.     func_listbox.config(yscrollcommand=scroll.set)
  53.  
  54.     window.bind('<Return>', enter_function)
  55.  
  56.     global func_choose, ent_first_coef, ent_second_coef
  57.     ent_first_coef = Entry(window, width='3')
  58.     ent_first_coef.place(x=150, y=751)
  59.  
  60.     text = Label(window, text='*', font=('Arial', 13, 'bold'))
  61.     text.place(x=174, y=751)
  62.  
  63.     functions = [
  64.                 'acos(x)', 'acosh(x)', 'asin(x)', 'asinh(x)', 'atan(x)', 'atan2(x)', 'atanh(x)', 'ceil(x)',
  65.                 'cos(x)', 'cosh(x)', 'exp(x)', 'expm1(x)', 'fabs(x)', 'factorial(x)', 'log(x)', 'log10(x)',
  66.                 'log1p(x)', 'log2(x)','sin(x)','sinh(x)', 'sqrt(x)', 'tan(x)', 'tanh(x)', 'tau(x)', 'trunc(x)'
  67.                 ]
  68.  
  69.     func_choose = ttk.Combobox(window, values=functions, width=10)
  70.     func_choose.place(x=190, y=750)
  71.  
  72.     text = Label(window, text='+', font=('Arial', 13))
  73.     text.place(x=273, y=748)
  74.  
  75.     ent_second_coef = Entry(window, width='3')
  76.     ent_second_coef.place(x=290, y=751)
  77.  
  78.     but_func_choose = Button(window, text='Сгенерировать', command=get_choosen_graphic_n_draw)
  79.     but_func_choose.place(x=185, y=780)
  80.  
  81.  
  82. def enter_function(event):
  83.     get_and_draw_graphic()
  84.  
  85.  
  86. def get_and_draw_graphic():
  87.     func = Graphic(ent_func.get())
  88.     if func.function in graphs:         # Проверка на наличия графика функции на графике
  89.         return
  90.     functions.append(func)
  91.     graphs.append(func.function)
  92.     draw_graphic(func)  # params = (middle_cord_x, middle_cord_y, delay)
  93.     update_listbox('ADD')
  94.  
  95.  
  96. def get_choosen_graphic_n_draw():
  97.     body_func = func_choose.get()
  98.     first_coef = ent_first_coef.get()
  99.     second_coef = ent_second_coef.get()
  100.  
  101.     if first_coef != '':
  102.         first_coef += ' * '
  103.  
  104.     if second_coef != '':
  105.         if '-' not in second_coef:
  106.             second_coef = ' + ' + second_coef
  107.         else:
  108.             second_coef = ' - ' + second_coef[1:]
  109.  
  110.     func = Graphic(first_coef + body_func + second_coef)
  111.  
  112.     if func.function in graphs:
  113.         return
  114.     functions.append(func)
  115.     draw_graphic(func)  # params = (middle_cord_x, middle_cord_y, delay)
  116.     update_listbox('ADD')
  117.  
  118.  
  119. def create_graphic_grid(delay, size=(1024, 720)):
  120.  
  121.     width = size[0]
  122.     height = size[1]
  123.  
  124.     middle_cord_x = (width)//2
  125.     middle_cord_y = (height)//2
  126.  
  127.     # Созадние осей графика
  128.     canvas.create_line(middle_cord_x, height, middle_cord_x, 0, width=3, arrow=LAST)
  129.     canvas.create_line(0, middle_cord_y, width, middle_cord_y, width=3, arrow=LAST)
  130.  
  131.     start_x = middle_cord_x % delay
  132.     start_y = middle_cord_y % delay
  133.  
  134.     # Создание сетки графика, меток и цифр
  135.     for i in range(start_x, width, delay):
  136.         canvas.create_line(i, 0, i, height, fill='grey')                        # Создание линий сетки по оси OY
  137.         canvas.create_line(i, middle_cord_y-5, i, middle_cord_y+6, width=3)     # Создание меток (разделителей на оси OX)
  138.         text = (middle_cord_x - i) // delay
  139.         canvas.create_text(i-5, middle_cord_y+10, text=-text, fill='#f10', font=('Arial', 8, 'bold')) # Создание цифр на разделителях оси OX
  140.  
  141.     for i in range(start_y, height, delay):
  142.         canvas.create_line(0, i, width, i, fill='grey')                         # Создание линий сетки по оси OX
  143.         canvas.create_line(middle_cord_x-5, i, middle_cord_x+6, i, width=3)     # Создание меток (разделителей на оси OY)
  144.         text = (middle_cord_y - i) // delay
  145.         if text == 0:
  146.             continue
  147.         canvas.create_text(middle_cord_x-10, i, text=text, fill='#f10', font=('Arial', 8, 'bold'))    # Создание цифр на разделителях оси OY
  148.  
  149.  
  150.     global params
  151.     params = (middle_cord_x, middle_cord_y, delay)
  152.  
  153.  
  154. def hideshow_graphic():
  155.     selection = func_listbox.curselection()
  156.     for index in selection:
  157.         func = functions[index]
  158.  
  159.         if func.hided == True:
  160.             show_graphic(func, index)
  161.         else:
  162.             hide_graphic(func, index)
  163.  
  164.  
  165. # Скрывает график удаляя линии рисунка
  166. def hide_graphic(func, index):
  167.     '''
  168.    args - func (Grpahic), index (Int)
  169.    return - None
  170.    '''
  171.     func.hided = True
  172.     delete_graphic_lines(func)
  173.     graphics.pop(func)
  174.     func_listbox.delete(index)
  175.     func_listbox.insert(index,' y = ' + func.function + ' СКРЫТ')
  176.  
  177.  
  178. # Перерисовывает скрытый график
  179. def show_graphic(func, index):
  180.     '''
  181.    args - func (Grpahic), index (Int)
  182.    return - None
  183.    '''
  184.     func.hided = False
  185.     draw_graphic(func)
  186.     func_listbox.delete(index)
  187.     func_listbox.insert(index,' y = ' + func.function)
  188.  
  189.  
  190. def delete_graphic_lines(func):
  191.     '''
  192.    args - func (Grpahic)
  193.    return - None
  194.    '''
  195.     for line in graphics[func]:
  196.         canvas.delete(line)
  197.  
  198.  
  199. # Стерает выбранный график или последний, если график не выбран
  200. def erase_graphic():
  201.     global functions
  202.     selection = func_listbox.curselection()
  203.  
  204.     if len(selection) == 0:
  205.         func = functions[-1]
  206.         functions.pop()
  207.         graphs.pop()
  208.         index_func = len(functions)
  209.         delete_graphic_lines(func)
  210.         if not func.hided:
  211.             graphics.pop(func)
  212.         update_listbox('DELETEFUNC', index_func)
  213.  
  214.     else:
  215.         deleted_index = []
  216.         for i in sorted(list(selection), reverse=True):
  217.             index_func = selection[i]
  218.             func = functions[i]
  219.  
  220.             if func.hided:
  221.                 functions.remove(func)
  222.                 graphs.remove(func.function)
  223.                 deleted_index.append(index_func)
  224.             else:
  225.                 functions.remove(func)
  226.                 graphs.remove(func.function)
  227.                 delete_graphic_lines(func)
  228.                 graphics.pop(func)
  229.                 deleted_index.append(index_func)
  230.  
  231.         deleted_index.sort(reverse=True)
  232.         for i in deleted_index:
  233.             update_listbox('DELETEFUNC', i)
  234.  
  235.  
  236. # Удаляет все графики, а также очищает массивы
  237. def erase_graphics():
  238.     global graphics, functions, graphs
  239.  
  240.     for function in graphics:
  241.         delete_graphic_lines(function)
  242.  
  243.     graphs = []
  244.     functions = []
  245.     graphics = {}
  246.     update_listbox('DELETEALL')
  247.  
  248.  
  249. def draw_graphic(func):
  250.     '''
  251.    Рисует график по точкам
  252.    args - func (Grpahic)
  253.    return - None
  254.    '''
  255.     graphic = []
  256.     x_dots = func.dots[0]
  257.     y_dots = func.dots[1]
  258.     for i in range(1, len(x_dots)-1):
  259.         if x_dots[i] != None and x_dots[i-1] != None:
  260.             last_x, last_y = set_coordinat(x_dots[i-1], y_dots[i-1], *params)
  261.             x, y = set_coordinat(x_dots[i], y_dots[i], *params)
  262.             graphic.append(canvas.create_line(last_x, last_y, x, y, width=3))
  263.     graphics[func] = graphic
  264.  
  265.  
  266. def set_coordinat(x, y, middle_cord_x, middle_cord_y, delay):
  267.     '''
  268.    Устанавливает координаты точки на графике
  269.    args - x (int), y (int), middle_cord_x (int), middle_cord_y (int), delay(int)
  270.    return - x (int), y (int)
  271.    '''
  272.     x = middle_cord_x + x*delay
  273.     y = middle_cord_y - (y*delay)
  274.     return x, y
  275.  
  276.  
  277. def update_listbox(action, index=None):
  278.     '''
  279.    args - action (str), index (int)
  280.    return - None
  281.    '''
  282.     # Удаляет все графики
  283.     if action == 'DELETEALL':
  284.         func_listbox.delete(0, func_listbox.size())
  285.     # Удаляет выбранный график
  286.     elif action == 'DELETEFUNC':
  287.         func_listbox.delete(index)
  288.     # Добавляет графиик
  289.     elif action == 'ADD':
  290.         func_listbox.insert(len(functions)-1, ' y = ' + functions[-1].function)
  291.  
  292.  
  293. def main():
  294.     global graphics, functions, graphs
  295.     graphics = {}
  296.     functions = []
  297.     graphs = []
  298.  
  299.     size_of_window = (1400, 1000)
  300.     root = Tk()
  301.     start = (10, 10)
  302.     initialize_window(root, 'Graphics', size_of_window)
  303.     initialize_widgets(root, start)
  304.  
  305.     delay = 40
  306.     create_graphic_grid(delay)
  307.     root.mainloop()
  308.  
  309.  
  310. if __name__ == "__main__":
  311.     main()
  312.  
  313. # made by Egor Golubev Lyceum №8
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement