Question

In: Computer Science

Sketch! This assignment is to write a Python program that makes use of the OpenGL graphics...

Sketch! This assignment is to write a Python program that makes use of the OpenGL graphics library to make an interactive sketching program that will allow the user to do line drawings. The user should be able to choose from a palette of colors displayed on the screen. When the user clicks the mouse in the color palette area, the drawing tool will switch to using the color selected, much like dipping a paint brush into a new color of paint.

Here are two starter codes. I'm trying to combine them basically but end up with a mess. It's supposed to be mimicking Microsoft Paint. Pick a color and then draw a line with it. There are 3 boxes on the left side, red, green, and blue. When the user clicks the box the line color matches the color of the box. Then the user can click in the space and free draw a line of that color, similar to Microsoft paint.









from OpenGL.GL import *
from OpenGL.GLUT import *
from OpenGL.GLU import *

# global variables
width = 400                 # window dimensions
height = 300

menuwidth = 100             # menu dimensions
ncolors = 3                 # number of colors
boxheight = height//ncolors # height of each color box

colormenu = [[1.0,0.0,0.0], [0.0,1.0,0.0], [0.0,0.0,1.0]]
menuindex = -1

###
#  Returns true if point (x, y) is in the color menu
###
def incolormenu(x, y):

   return x >= 0 and x <= menuwidth and y >= 0 and y <= height


###
# Returns index of point (x, y) in the color menu
###
def colormenuindex(x, y):

   if not incolormenu(x, y):
      return -1;
   else:
      return y//boxheight


###
# Watch mouse button presses and handle them
###
def handleButton(button, state, x, y):

   global menuindex

   y = height - y   # reverse y, so zero at bottom, and max at top

   if button != GLUT_LEFT_BUTTON:   # ignore all but left button
      return

  
   # if button pressed and released in same menu box, then update
   # the color of the large square
  
   if state == GLUT_DOWN:
      if incolormenu(x, y):
         menuindex = colormenuindex(x, y)
   else:
      if incolormenu(x, y) and colormenuindex(x, y) == menuindex:
         glColor3f(colormenu[menuindex][0], colormenu[menuindex][1], colormenu[menuindex][2])
         glRecti(menuwidth, 0, width, height)

   glFlush()


###
# Draw the colored box and the color menu
###
def drawMenu():
   
   # clear window
   glClear(GL_COLOR_BUFFER_BIT)

   # draw the color menu
   for i in range(ncolors):
      glColor3f(colormenu[i][0], colormenu[i][1], colormenu[i][2])
      glRecti(1, boxheight * i + 1, menuwidth - 1, boxheight * (i + 1) - 1)
  
   glFlush()

###
#  Main program
###
def main():

   glutInit()

   glutInitDisplayMode(GLUT_SINGLE | GLUT_RGBA)
   glutInitWindowSize(width, height)
   window = glutCreateWindow("Color Menu")

   # callback routine
   glutDisplayFunc(drawMenu)
   glutMouseFunc(handleButton)

   # lower left of window is (0, 0), upper right is (width, height)
   gluOrtho2D(0, width, 0, height)

   # specify window clear (background) color to be black
   glClearColor(0, 0, 0, 0)
 
   glutMainLoop()

if __name__ == "__main__":
   main()





from OpenGL.GL import *
from OpenGL.GLUT import *
from OpenGL.GLU import *

# global variables
width = 600        # window dimensions
height = 600

wleft = 0
wright = width
wbottom = 0
wtop = height

tracking = False

###
# Returns true if point (x, y) is in the window
###
def inwindow(x, y):

   return x > wleft and x < wright and y > wbottom and y < wtop

###
# Draw a line to new mouse position
###
def m_Motion(x, y):

   y = wtop - y

   if tracking and inwindow(x, y):
      glBegin(GL_LINES)
      glVertex2i(width//2, height//2)
      glVertex2i(x, y)
      glEnd()
    
   glFlush()

###
# Watch mouse button presses and handle them
###
def handleButton(button, state, x, y):
  
   global tracking

   y = wtop - y

   if button != GLUT_LEFT_BUTTON:
      return

   if state == GLUT_DOWN:
      if inwindow(x, y):
         tracking = True
   else:
      tracking = False

###
# Clear the window
###
def drawMouse():
  
   glClear(GL_COLOR_BUFFER_BIT)     # clear the window

   glColor3f(0, 0, 0)              # set mouse line color
  
   glFlush()

###
#  Main program
###
def main():

   glutInit()

   glutInitDisplayMode(GLUT_SINGLE | GLUT_RGBA)
   glutInitWindowSize(width, height)
   window = glutCreateWindow("Mouse Exam")

   # callback routine
   glutDisplayFunc(drawMouse)
   glutMouseFunc(handleButton)
   glutMotionFunc(m_Motion)

   # lower left of window is (0, 0), upper right is (width, height)
   gluOrtho2D(0, width, 0, height)

   # specify window clear (background) color to be dark grey
   glClearColor(0.7, 0.7, 0.7, 1)
 
   glutMainLoop()

if __name__ == "__main__":
   main()

Solutions

Expert Solution

from tkinter import *
from tkinter.colorchooser import askcolor


class Paint(object):

DEFAULT_PEN_SIZE = 5.0
DEFAULT_COLOR = 'black'

def __init__(self):
self.root = Tk()

self.pen_button = Button(self.root, text='pen', command=self.use_pen)
self.pen_button.grid(row=0, column=0)

self.brush_button = Button(self.root, text='brush', command=self.use_brush)
self.brush_button.grid(row=0, column=1)

self.color_button = Button(self.root, text='color', command=self.choose_color)
self.color_button.grid(row=0, column=2)

self.eraser_button = Button(self.root, text='eraser', command=self.use_eraser)
self.eraser_button.grid(row=0, column=3)

self.choose_size_button = Scale(self.root, from_=1, to=10, orient=HORIZONTAL)
self.choose_size_button.grid(row=0, column=4)

self.c = Canvas(self.root, bg='white', width=600, height=600)
self.c.grid(row=1, columnspan=5)

self.setup()
self.root.mainloop()

def setup(self):
self.old_x = None
self.old_y = None
self.line_width = self.choose_size_button.get()
self.color = self.DEFAULT_COLOR
self.eraser_on = False
self.active_button = self.pen_button
self.c.bind('<B1-Motion>', self.paint)
self.c.bind('<ButtonRelease-1>', self.reset)

def use_pen(self):
self.activate_button(self.pen_button)

def use_brush(self):
self.activate_button(self.brush_button)

def choose_color(self):
self.eraser_on = False
self.color = askcolor(color=self.color)[1]

def use_eraser(self):
self.activate_button(self.eraser_button, eraser_mode=True)

def activate_button(self, some_button, eraser_mode=False):
self.active_button.config(relief=RAISED)
some_button.config(relief=SUNKEN)
self.active_button = some_button
self.eraser_on = eraser_mode

def paint(self, event):
self.line_width = self.choose_size_button.get()
paint_color = 'white' if self.eraser_on else self.color
if self.old_x and self.old_y:
self.c.create_line(self.old_x, self.old_y, event.x, event.y,
width=self.line_width, fill=paint_color,
capstyle=ROUND, smooth=TRUE, splinesteps=36)
self.old_x = event.x
self.old_y = event.y

def reset(self, event):
self.old_x, self.old_y = None, None


if __name__ == '__main__':
Paint()


Related Solutions

* Write a program texttriangle.py. in python This, too, is not a graphics program. Prompt the...
* Write a program texttriangle.py. in python This, too, is not a graphics program. Prompt the user for a small positive integer value, that I’ll call n. Then use a for-loop with a range function call to make a triangular arrangement of ‘#’characters, with n ‘#’ characters in the last line. Hint: [5] Then leave a blank line. Then make a similar triangle, except start with the line with n ‘#’ characters. To make the second triangle, you can use...
Write the code in python only. You will need the graphics library for this assignment. Please...
Write the code in python only. You will need the graphics library for this assignment. Please download the library and place it in the same file as your solution. Draw a 12" ruler on the screen. A ruler is basically a rectangular outline with tick marks extending from the top edge. The tick marks should be drawn at each quarter-inch mark. Below the tick marks, your ruler should show large integers at each full-inch position.
For Python: In this assignment you are asked to write a Python program to determine the...
For Python: In this assignment you are asked to write a Python program to determine the Academic Standing of a studentbased on their CGPA. The program should do the following: Prompt the user to enter his name. Prompt the user to enter his major. Prompt the user to enter grades for 3 subjects (A, B, C, D, F). Calculate the CGPA of the student. To calculate CGPA use the formula: CGPA = (quality points * credit hours) / credit hours...
(PYTHON) Write a program: This assignment will give you more experience on the use of: 1....
(PYTHON) Write a program: This assignment will give you more experience on the use of: 1. integers (int) 2. floats (float) 3. conditionals 4. iteration The goal of this project is to make a fictitious comparison of the federal income. You will ask the user to input their taxable income. Use the income brackets given below to calculate the new and old income tax. For the sake of simplicity of the project we will only consider individuals and not married...
Write a Python graphics program that draws the following shapes: • window size: 250 x 250...
Write a Python graphics program that draws the following shapes: • window size: 250 x 250 pixels with window title with your name • big circle, 50 pixels radius with center at (125, 125) • two green circles, 10 pixels radius; first one centered at (113, 113) and second centered at (137, 113) • one red line, from (100, 150) to (150, 150) Then answer this, what do you see? (make this a comment in your code)
Using Python, Assignment Write a program that plays a game of craps. The program should allow...
Using Python, Assignment Write a program that plays a game of craps. The program should allow the player to make a wager before each “turn”. Before each turn, allow the user to either place a bet or exit the game. After each turn display the player’s current balance. Specifics Each player will start with $500.00. Initially, and after each turn give the user the option of betting or leaving the program. Implement this any way you wish, but make it...
Description of the Assignment: Write a Python program to (a) create a new empty stack. Then,...
Description of the Assignment: Write a Python program to (a) create a new empty stack. Then, (b) add items onto the stack. (c) Print the stack contents. (d) Remove an item off the stack, and (e) print the removed item. At the end, (f) print the new stack contents: Please use the following comments in your python script: # ************************************************* # COP3375 # Student's full name ( <<< your name goes here) # Week 8: Assignment 1 # ************************************************* #...
1. INTRODUCTION The goal of this programming assignment is for students to write a Python program...
1. INTRODUCTION The goal of this programming assignment is for students to write a Python program that uses repetition (i.e. “loops”) and decision structures to solve a problem. 2. PROBLEM DEFINITION  Write a Python program that performs simple math operations. It will present the user with a menu and prompt the user for an option to be selected, such as: (1) addition (2) subtraction (3) multiplication (4) division (5) quit Please select an option (1 – 5) from the...
Assignment Write a program using turtle graphics which writes your initials, or any other three unique...
Assignment Write a program using turtle graphics which writes your initials, or any other three unique letters, to the display. Look to your program for lab 1 for reminders of how to use turtle graphics. Functions that must be written: def drawLetter (x, y, letterColor): Write three functions, one for three unique letters. Personally, I would write drawA, drawR, and drawS. Each function must draw that letter to the screen. The x and y values determine the upper left-hand location...
Write a program IN PYTHON of the JUPYTER NOOTBOOK Write a Python program that gets a...
Write a program IN PYTHON of the JUPYTER NOOTBOOK Write a Python program that gets a numeric grade (on a scale of 0-100) from the user and convert it to a letter grade based on the following table. A: 90% - 100% B 80% - 89% C 70% - 79% D 60% - 69% F <60% The program should be written so that if the user entered either a non-numeric input or a numeric input out of the 0-100 range,...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT