import tkinter as tk
from tkinter.colorchooser import askcolor
from functools import partial
class App(tk.Tk):
def __init__(self):
super().__init__()
self.movefrom = []
self.moveto = []
self.geometry('500x500')
self.color = None
self.canvas = tk.Canvas(self, bg='white')
self.coordinates = tk.Label(self)
self.prnt_color = tk.Label(self)
self.button_color = tk.Button(self, text='choose_color',
command=partial(self.ask_color, "fg"))
self.canvas.bind('<Button-1>', self.mouse_motion)
self.canvas.bind('<Button-3>', self.mouse_motion2)
self.canvas.pack()
self.coordinates.pack()
self.prnt_color.pack()
self.button_color.pack(padx=20, pady=20)
def mouse_motion(self, event):
self.movefrom.append(event.x)
self.movefrom.append(event.y)
text = f'x={event.x}, y={event.y}'
self.coordinates.config(text=text)
def mouse_motion2(self, event):
self.moveto.append(event.x)
self.moveto.append(event.y)
text = f'x={event.x}, y={event.y}'
self.coordinates.config(text=text)
self.canvas.create_line(self.movefrom[0], self.movefrom[1],
self.moveto[0], self.moveto[1],
fill=self.color, width=10)
self.movefrom = []
self.moveto = []
def ask_color(self, option):
ask = askcolor()[1]
print('выбран цвет {ask}')
self.prnt_color.config(text=ask)
self.color = ask
if __name__ == '__main__':
app = App()
app.mainloop()
self.canvas.bind('<Button-1>', self.mouse_motion)
self.canvas.bind('<Button-3>', self.mouse_motion2)
self.canvas.pack()
self.coordinates.pack()
self.prnt_color.pack()
self.button_color.pack(padx=20, pady=20)
- я бы вынес это в одельную функцию, которою уже вызывает __init__, хотя это опционально.