Advertisement
jimkilled

graphics v3

Dec 11th, 2020 (edited)
735
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 8.89 KB | None | 0 0
  1. from tkinter import *
  2. from math import *
  3.  
  4.  
  5. def initialize_window(window, title, size=(1024, 720), sizable=(False, False)):
  6.     '''
  7.    Устанавливает заголовок окна, размеры по осям X, Y и устанавливает возможность изменения по осям X, Y
  8.    args - window (Tk), title (str), size (tuple(int, int)), sizable (tuple(bool, bool))
  9.    return - None
  10.    '''
  11.     window.title(title)
  12.     window.geometry(f'{size[0]}x{size[1]}')
  13.     window.resizable(sizable[0], sizable[1])
  14.  
  15.  
  16. def initialize_widgets(window, start, size=(1024, 720)):
  17.     global canvas
  18.     canvas = Canvas(window, bg='#fff', width=size[0], height=size[1])
  19.     canvas.place(x=start[0], y=start[1])
  20.  
  21.     text = Label(window, text='y = ', font=('Arial', 13, 'bold'))
  22.     text.place(x=1130, y=347)
  23.  
  24.     global ent_func
  25.     ent_func = Entry(window, width='20')
  26.     ent_func.place(x=1168, y=350)
  27.  
  28.     but_func = Button(window, text='Сгенерировать', command=get_and_draw_graphic)
  29.     but_func.place(x=1175, y=374)
  30.  
  31.     but_erase_last_func = Button(window, text='Стереть', command=erase_graphic)
  32.     but_erase_last_func.place(x=1175, y=400)
  33.  
  34.     but_erase_all = Button(window, text='Стереть всё', command=erase_graphics)
  35.     but_erase_all.place(x=1175, y=426)
  36.  
  37.     but_hide_graph = Button(window, text='Скрыть', command=hide_graphic)
  38.     but_hide_graph.place(x=1175, y=452)
  39.  
  40.     global func_listbox
  41.     func_listbox = Listbox(window, width=30, height=20, selectmode=EXTENDED)
  42.     func_listbox.place(x=1145, y=20)
  43.  
  44.     scroll = Scrollbar(window, command=func_listbox.yview, orient=VERTICAL)
  45.     scroll.place(x=1329, y=20)
  46.  
  47.     func_listbox.config(yscrollcommand=scroll.set)
  48.  
  49.     window.bind('<Return>', enter_function)
  50.  
  51.  
  52. def create_graphic_grid(delay, size=(1024, 720)):
  53.  
  54.     width = size[0]
  55.     height = size[1]
  56.  
  57.     middle_cord_x = (width)//2
  58.     middle_cord_y = (height)//2
  59.  
  60.     # Созадние осей графика
  61.     canvas.create_line(middle_cord_x, height, middle_cord_x, 0, width=3, arrow=LAST)
  62.     canvas.create_line(0, middle_cord_y, width, middle_cord_y, width=3, arrow=LAST)
  63.  
  64.     start_x = middle_cord_x % delay
  65.     start_y = middle_cord_y % delay
  66.  
  67.     # Создание сетки графика
  68.     # for i in range(start_x, width, delay):
  69.     #     canvas.create_line(i, y0, i, height, fill='grey')
  70.     # for i in range(start_y, height, delay):
  71.     #     canvas.create_line(x0, i, width, i, fill='grey')
  72.  
  73.     # Создание сетки графика, меток и цифр
  74.     for i in range(start_x, width, delay):
  75.         canvas.create_line(i, 0, i, height, fill='grey')                        # Создание линий сетки по оси OY
  76.         canvas.create_line(i, middle_cord_y-5, i, middle_cord_y+6, width=3)     # Создание меток (разделителей на оси OX)
  77.         text = (middle_cord_x - i) // delay
  78.         canvas.create_text(i-5, middle_cord_y+10, text=-text, fill='#f10', font=('Arial', 8, 'bold')) # Создание цифр на разделителях оси OX
  79.  
  80.     for i in range(start_y, height, delay):
  81.         canvas.create_line(0, i, width, i, fill='grey')                         # Создание линий сетки по оси OX
  82.         canvas.create_line(middle_cord_x-5, i, middle_cord_x+6, i, width=3)     # Создание меток (разделителей на оси OY)
  83.         text = (middle_cord_y - i) // delay
  84.         if text == 0:
  85.             continue
  86.         canvas.create_text(middle_cord_x-10, i, text=text, fill='#f10', font=('Arial', 8, 'bold'))    # Создание цифр на разделителях оси OY
  87.  
  88.  
  89.     global params
  90.     params = (middle_cord_x, middle_cord_y, delay)
  91.  
  92. def enter_function(event):
  93.     get_and_draw_graphic()
  94.  
  95.  
  96. # Скрывает график удаляя линии рисунка
  97. def hide_graphic():
  98.     selection = func_listbox.curselection()
  99.     for i in range(len(selection)):
  100.         index_func = selection[i]
  101.         func = func_listbox.get(selection[i])[5:]
  102.  
  103.         if ' СКРЫТ' in func:
  104.             func = func[:-6]
  105.             show_graphic(func, index_func)
  106.  
  107.         else:
  108.             hided_graphics.append(func)
  109.             # Стерание графика выбранного графика
  110.             for line in graphics[func]:
  111.                 canvas.delete(line)
  112.  
  113.             graphics.pop(func)
  114.             func_listbox.delete(index_func)
  115.             func_listbox.insert(index_func,' y = ' + func + ' СКРЫТ')
  116.  
  117.  
  118. # Перерисовывает скрытый график
  119. def show_graphic(func, index_func):
  120.     hided_graphics.remove(func)
  121.     create_graphic(func, *params)
  122.     func_listbox.delete(index_func)
  123.     func_listbox.insert(index_func,' y = ' + func)
  124.  
  125.  
  126. def get_and_draw_graphic():
  127.     func = ent_func.get()
  128.     if func in functions:
  129.         return
  130.     functions.append(func)
  131.     create_graphic(func, *params)  # params = (middle_cord_x, middle_cord_y, delay)
  132.     update_listbox('ADD')
  133.  
  134.  
  135. # Стерает выбранный график или последний, если график не выбран
  136. def erase_graphic():
  137.     global functions, hided_graphics
  138.     selection = func_listbox.curselection()
  139.  
  140.     if len(selection) == 0:
  141.         func = functions[-1]
  142.  
  143.         if func in hided_graphics:
  144.             return
  145.  
  146.         functions.pop()
  147.         index_func = len(functions)
  148.  
  149.         for line in graphics[func]:
  150.             canvas.delete(line)
  151.  
  152.         graphics.pop(func)
  153.         update_listbox('DELETEFUNC', index_func)
  154.  
  155.     else:
  156.         deleted_index = []
  157.         for i in selection:
  158.             index_func = selection[i]
  159.             func = func_listbox.get(selection[i])[5:]
  160.  
  161.             if ' СКРЫТ' in func:
  162.                 func = func[:-6]
  163.                 functions.remove(func)
  164.                 hided_graphics.remove(func)
  165.                 deleted_index.append(index_func)
  166.                
  167.             else:
  168.                 functions.remove(func)
  169.  
  170.                 for line in graphics[func]:
  171.                     canvas.delete(line)
  172.  
  173.                 graphics.pop(func)
  174.                 deleted_index.append(index_func)
  175.  
  176.         deleted_index.sort(reverse=True)
  177.         for i in deleted_index:
  178.             update_listbox('DELETEFUNC', i)
  179.  
  180.  
  181.  
  182. # def erase_last_graphic():
  183. #     last_func = functions[len(functions)-1]
  184. #     functions.pop()
  185. #     for line in graphics[last_func]:
  186. #         canvas.delete(line)
  187. #     graphics.pop(last_func)
  188. #     update_listbox('DELETELAST')
  189.  
  190. # Удаляет все графики, а также очищает массивы
  191. def erase_graphics():
  192.     global graphics, functions
  193.  
  194.     for function in graphics:
  195.         for line in graphics[function]:
  196.             canvas.delete(line)
  197.  
  198.     hided_graphics = []
  199.     functions = []
  200.     graphics = {}
  201.     update_listbox('DELETEALL')
  202.  
  203.  
  204. def create_graphic(func, middle_cord_x, middle_cord_y, delay):
  205.     graphic = []
  206.     for x in range(-10000, 10000):
  207.         try:
  208.             last_x = (x - 1)/100
  209.             last_y = set_y_func_value(last_x, func)
  210.             x /= 100                                   # Уменьшение x для получения более точного рисунка графика
  211.             y = set_y_func_value(x, func)
  212.             last_x, last_y = set_coordinat(last_x, last_y, middle_cord_x, middle_cord_y, delay)
  213.             # x = middle_cord_x + x*delay
  214.             # y = middle_cord_y - (y*delay)
  215.             x, y = set_coordinat(x, y, middle_cord_x, middle_cord_y, delay)
  216.             graphic.append(canvas.create_line(last_x, last_y, x, y, width=3))
  217.         except:
  218.             continue
  219.     graphics[func] = graphic
  220.  
  221.  
  222. def set_y_func_value(x, func):
  223.     # Преобразование текстовой функции в исполняемый код
  224.     y = eval(func)
  225.     return y
  226.  
  227.  
  228. def set_coordinat(x, y, middle_cord_x, middle_cord_y, delay):
  229.     x = middle_cord_x + x*delay
  230.     y = middle_cord_y - (y*delay)
  231.     return x, y
  232.  
  233.  
  234. def update_listbox(action, index=None):
  235.     # Удаляет все графики
  236.     if action == 'DELETEALL':
  237.         func_listbox.delete(0, func_listbox.size())
  238.     # Удаляет выбранный график
  239.     elif action == 'DELETEFUNC':
  240.         func_listbox.delete(index)
  241.     # Добавляет графиик
  242.     elif action == 'ADD':
  243.         func_listbox.insert(len(functions)-1, ' y = ' + str(functions[-1]) )
  244.  
  245.  
  246. def main():
  247.     global size
  248.     global graphics, functions, hided_graphics
  249.     graphics = {}
  250.     functions = []
  251.     hided_graphics =[]
  252.  
  253.     size_of_window = (1400, 1000)
  254.     root = Tk()
  255.     start = (10, 10)
  256.     initialize_window(root, 'Graphics', size_of_window)
  257.     initialize_widgets(root, start)
  258.  
  259.     delay = 40
  260.     create_graphic_grid(delay)
  261.     root.mainloop()
  262.  
  263.  
  264. if __name__ == "__main__":
  265.     main()
  266.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement