Example #1
26
    def initUI(self):
      
        self.parent.title("Shapes")        
        self.pack(fill=BOTH, expand=1)

        canvas = Canvas(self)
        canvas.create_oval(10, 10, 80, 80, outline="red", 
            fill="green", width=2)
        #Here the create_oval() method is used to create a circle item. 
        #The first four parameters are the bounding box coordinates of the circle. 
        #In other words, they are x and y coordinates of the top-left and bottom-right points of the box, 
        #in which the circle is drawn.
        canvas.create_oval(110, 10, 210, 80, outline="#f11", 
            fill="#1f1", width=2)
        canvas.create_rectangle(230, 10, 290, 60, 
            outline="#f11", fill="#1f1", width=2)
        #We create a rectangle item. 
        #The coordinates are again the bounding box of the rectangle to be drawn.
        canvas.create_arc(30, 200, 90, 100, start=0, 
            extent=210, outline="#f11", fill="#1f1", width=2)
        #This code line creates an arc. 
        #An arc is a part of the circumference of the circle. 
        #We provide the bounding box. 
        #The start parameter is the start angle of the arc. 
        #The extent is the angle size.
            
        points = [150, 100, 200, 120, 240, 180, 210, 
            200, 150, 150, 100, 200]
        canvas.create_polygon(points, outline='red', 
            fill='green', width=2)
        #A polygon is created. 
        #It is a shape with multiple corners. 
        #To create a polygon in Tkinter, we provide the list of polygon coordinates to the create_polygon() method.
        
        canvas.pack(fill=BOTH, expand=1)
Example #2
0
class Wall(object):
    MIN_RED = MIN_GREEN = MIN_BLUE = 0x0
    MAX_RED = MAX_GREEN = MAX_BLUE = 0xFF

    PIXEL_WIDTH = 96

    def __init__(self, width, height):
        self.width = width
        self.height = height
        self._tk_init()
        self.pixels = [(0, 0, 0) for i in range(self.width * self.height)]

    def _tk_init(self):
        self.root = Tk()
        self.root.title("ColorWall %d x %d" % (self.width, self.height))
        self.root.resizable(0, 0)
        self.frame = Frame(self.root, bd=5, relief=SUNKEN)
        self.frame.pack()

        self.canvas = Canvas(self.frame,
                             width=self.PIXEL_WIDTH * self.width,
                             height=self.PIXEL_WIDTH * self.height,
                             bd=0, highlightthickness=0)
        self.canvas.pack()
        self.root.update()

    def set_pixel(self, x, y, hsv):
        self.pixels[self.width * y + x] = hsv

    def get_pixel(self, x, y):
        return self.pixels[self.width * y + x]

    def draw(self):
        self.canvas.delete(ALL)
        for x in range(len(self.pixels)):
            x_0 = (x % self.width) * self.PIXEL_WIDTH
            y_0 = (x / self.width) * self.PIXEL_WIDTH
            x_1 = x_0 + self.PIXEL_WIDTH
            y_1 = y_0 + self.PIXEL_WIDTH
            hue = "#%02x%02x%02x" % self._get_rgb(self.pixels[x])
            self.canvas.create_rectangle(x_0, y_0, x_1, y_1, fill=hue)
        self.canvas.update()

    def clear(self):
        for i in range(self.width * self.height):
            self.pixels[i] = (0, 0, 0)

    def _hsv_to_rgb(self, hsv):
        rgb = colorsys.hsv_to_rgb(*hsv)
        red = self.MAX_RED * rgb[0]
        green = self.MAX_GREEN * rgb[1]
        blue = self.MAX_BLUE * rgb[2]
        return (red, green, blue)

    def _get_rgb(self, hsv):
        red, green, blue = self._hsv_to_rgb(hsv)
        red = int(float(red) / (self.MAX_RED - self.MIN_RED) * 0xFF)
        green = int(float(green) / (self.MAX_GREEN - self.MIN_GREEN) * 0xFF)
        blue = int(float(blue) / (self.MAX_BLUE - self.MIN_BLUE) * 0xFF)
        return (red, green, blue)
Example #3
0
class GUI:
    def __init__(self, title, width, height):
        from Tkinter import Tk, Canvas, Toplevel
        self.width = width
        self.height = height
        self.title = title
        self.app = Tk()
        self.app.withdraw()
        self.win = Toplevel()
        self.win.wm_title(title)
        self.canvas = Canvas(self.win,
                             width=(self.width * 2),
                             height=(self.height * 2))
        self.canvas.pack(side='bottom', expand="yes", anchor="n", fill='both')
        self.win.winfo_toplevel().protocol('WM_DELETE_WINDOW', self.close)
        #self.canvas.bind("<Configure>", self.changeSize)

    def close(self):
        self.app.destroy()

    def draw(self, lat, length):
        print "Drawing...",
        for h in range(length):
            for w in range(self.width):
                if lat.data[h][w]:
                    self.canvas.create_rectangle(w * 2,
                                                 h * 2,
                                                 w * 2 + 2,
                                                 h * 2 + 2,
                                                 fill="black")
            self.win.update_idletasks()
        print "Done!"
Example #4
0
 def __draw_continuous_view(self,
                            min_val,
                            max_val,
                            value_matrix,
                            scheme,
                            n_classes,
                            is_simulation_view=False):
     """
     :param min_val:
     :param max_val:
     :param value_matrix:
     :param scheme:
     :param n_classes:
     :param is_simulation_view:
     :return:
     """
     side = self.__square_side
     for i in xrange(self.__n_rows):
         for j in xrange(self.__n_cols):
             if is_simulation_view and value_matrix[i][j] <= 0:
                 continue
             x = self.__start_x + j * side
             y = self.__start_y + i * side
             color = View.calculate_color(min_val, max_val, n_classes,
                                          value_matrix[i][j], scheme)
             Canvas.create_rectangle(self,
                                     x,
                                     y,
                                     x + side,
                                     y + side,
                                     fill=color)
Example #5
0
class LandscapeGUI(Frame):
    def __init__(self, parent):
        self.HEIGHT = 1000
        self.WIDTH = 1000
        self.parent = parent
        self.parent.title("MAZE")
        self.canvas = Canvas(height=self.HEIGHT, width=self.WIDTH, bg='white')
        self.canvas.pack(fill=BOTH, expand=True)

    def paint_map(self, matrix):
        deltax = self.HEIGHT / len(matrix)
        deltay = self.WIDTH / len(matrix[0])
        rows = len(matrix)
        cols = len(matrix[0])
        for i in range(0, rows):
            for j in range(0, cols):
                if (matrix[i][j] == Terrain.FLAT):
                    _cell_color = 'white'
                elif (matrix[i][j] == Terrain.HILLY):
                    _cell_color = 'grey'
                elif (matrix[i][j] == Terrain.FOREST):
                    _cell_color = 'pink'
                else:
                    _cell_color = 'green'

                self._paint_cell(i, j, _cell_color, deltax, deltay)

    def _paint_cell(self, rw, cl, color, deltax, deltay):
        x0 = cl * deltax
        x1 = x0 + deltax
        y0 = rw * deltay
        y1 = y0 + deltay
        self.canvas.create_rectangle(x0, y0, x1, y1, fill=color, tags="cursor")
Example #6
0
    def plot_results(self):
        grid_x = (self.canvas_width -
                  2 * self.canvas_margin) / (self.grid_size)
        grid_y = (self.canvas_height -
                  2 * self.canvas_margin) / (self.grid_size)
        pin_dx = grid_x / 6
        pin_dy = grid_y / 6

        master = Tk()

        w = Canvas(master, width=self.canvas_width, height=self.canvas_height)
        w.pack()

        for node in self.graph:
            i, j = self.id_to_coord(node)
            if node[-1] == 's':
                i += 0.5
                j += 0.5
            nx, ny = self.get_xy(i, j)
            if node[-1] == 's':
                fill_col = 'green'
                w.create_rectangle(nx - pin_dx,
                                   ny - pin_dy,
                                   nx + pin_dx,
                                   ny + pin_dy,
                                   fill=fill_col)
            else:
                fill_col = 'black'
                w.create_oval(nx - 2, ny - 2, nx + 2, ny + 2, fill=fill_col)

        self.draw_routes(w)

        w.update()
        w.postscript(file='sol35.ps', colormode='color')
        mainloop()
Example #7
0
class GUI:
    def __init__(self, title, width, height):
        from Tkinter import Tk, Canvas, Toplevel
        self.width = width
        self.height = height
        self.title = title
        self.app = Tk()
        self.app.withdraw()
        self.win = Toplevel()
        self.win.wm_title(title)
        self.canvas = Canvas(self.win,
                             width=(self.width * 2),
                             height=(self.height * 2))
        self.canvas.pack(side = 'bottom', expand = "yes", anchor = "n",
                         fill = 'both')
        self.win.winfo_toplevel().protocol('WM_DELETE_WINDOW',self.close)
        #self.canvas.bind("<Configure>", self.changeSize)
        
    def close(self):
        self.app.destroy()

    def draw(self, lat, length):
        print "Drawing...",
        for h in range(length):
            for w in range(self.width):
                if lat.data[h][w]:
                    self.canvas.create_rectangle(w*2, h*2, w*2+2, h*2+2,
                                                 fill = "black")
            self.win.update_idletasks()
        print "Done!"
class SimpleGrid(Frame):
	
	def __init__(self, parent, props):
		Frame.__init__(self,parent)
		
		self.parent = parent
		self.iWidth = props['width']
		self.iHeight = props['height']
		self.nCols = props['cols']
		self.nRows = props['rows']
		self.gWidthPercent = 0.90
		self.gHeightPercent = 0.90

		self.gridSqWidth = 0
		self.gridSqHeight = 0
		self.gridX = 0
		self.gridY = 0
		
		self.initGrid()
		
	def initGrid(self):
		self.parent.title("SimpleGrid")
		self.pack(fill=BOTH, expand=1)
		self.buildCanvas()
		self.calculateDimensions()
		self.enableEvents()
		
	def calculateDimensions(self):
	
		# calculate the size of the grid squares
		self.gridSqWidth = (self.gWidthPercent * self.iWidth) / self.nCols
		self.gridSqHeight = (self.gHeightPercent * self.iHeight) / self.nRows
	
		# calculate the upper left corner
		self.gridX = (1.0 - self.gWidthPercent) * self.iWidth / 2.0
		self.gridY = (1.0 - self.gHeightPercent) * self.iHeight / 2.0
		
	def buildCanvas(self):
		self.canvas = Canvas(self)
		
	def draw(self):		
		
		for i in range(0,self.nRows):
			for j in range(0,self.nCols):
				self.drawSquare(i,j)
		
		self.canvas.pack(fill=BOTH, expand=1)
		
	def drawSquare(self,row,col):
		sqX = self.gridX + (self.gridSqWidth*col)
		sqY = self.gridY + (self.gridSqHeight*row)
		self.canvas.create_rectangle(sqX, sqY,
									 sqX + self.gridSqWidth,
									 sqY + self.gridSqHeight,
									 outline="black")
		
		
	def enableEvents(self):
		# do nothing -- let child classes do this
		return
class SimpleGrid(Frame):
    def __init__(self, parent, props):
        Frame.__init__(self, parent)

        self.parent = parent
        self.iWidth = props['width']
        self.iHeight = props['height']
        self.nCols = props['cols']
        self.nRows = props['rows']
        self.gWidthPercent = 0.90
        self.gHeightPercent = 0.90

        self.gridSqWidth = 0
        self.gridSqHeight = 0
        self.gridX = 0
        self.gridY = 0

        self.initGrid()

    def initGrid(self):
        self.parent.title("SimpleGrid")
        self.pack(fill=BOTH, expand=1)
        self.buildCanvas()
        self.calculateDimensions()
        self.enableEvents()

    def calculateDimensions(self):

        # calculate the size of the grid squares
        self.gridSqWidth = (self.gWidthPercent * self.iWidth) / self.nCols
        self.gridSqHeight = (self.gHeightPercent * self.iHeight) / self.nRows

        # calculate the upper left corner
        self.gridX = (1.0 - self.gWidthPercent) * self.iWidth / 2.0
        self.gridY = (1.0 - self.gHeightPercent) * self.iHeight / 2.0

    def buildCanvas(self):
        self.canvas = Canvas(self)

    def draw(self):

        for i in range(0, self.nRows):
            for j in range(0, self.nCols):
                self.drawSquare(i, j)

        self.canvas.pack(fill=BOTH, expand=1)

    def drawSquare(self, row, col):
        sqX = self.gridX + (self.gridSqWidth * col)
        sqY = self.gridY + (self.gridSqHeight * row)
        self.canvas.create_rectangle(sqX,
                                     sqY,
                                     sqX + self.gridSqWidth,
                                     sqY + self.gridSqHeight,
                                     outline="black")

    def enableEvents(self):
        # do nothing -- let child classes do this
        return
Example #10
0
class DCGreenLanternWidget(Frame):
    """
    Green Lantern logo from DC comics
    (yeah yeah, i'm shitty artist, i know)
    """
    green = "#07A007"
    outline = "#FFFFFF"
    unpowered = '#C0C0C0'

    def __init__(self, parent, initial_state):
        Frame.__init__(self, parent)
        self.pack(fill=BOTH, expand=1)

        self.canvas = Canvas(self, cnf={'background': BACKGROUND_COLOR})

        # outer circle
        kw = {'outline': self.outline, 'fill': self.green}
        base = 30 * SCALE
        d = 190 * SCALE
        s = 10 * SCALE
        outer_circle = ((base, base, base + d - s, base + d),
                        (base + s, base + s, base + d - s - s, base + d - s))
        self.canvas.create_oval(*outer_circle[0], **kw)

        kw['fill'] = BACKGROUND_COLOR
        self.canvas.create_oval(*outer_circle[1], **kw)

        # inner circle
        kw = {'outline': self.outline, 'fill': self.green}
        base = 70 * SCALE
        d = 100 * SCALE
        s = 14 * SCALE
        outer_circle = ((base, base + s, base + d, base + d),
                        (base + s, base + s + s, base + d - s, base + d - s))
        self.canvas.create_oval(*outer_circle[0], **kw)

        kw['fill'] = initial_state[1] if initial_state[0] else self.unpowered
        self.item = self.canvas.create_oval(*outer_circle[1], **kw)

        # top bar
        self.canvas.create_rectangle(base,
                                     base,
                                     base + d,
                                     base + s,
                                     outline=self.green,
                                     fill=self.green)

        # bottom bar
        self.canvas.create_rectangle(base,
                                     base + d,
                                     base + d,
                                     base + d + s,
                                     outline=self.green,
                                     fill=self.green)
        self.canvas.pack(fill=BOTH, expand=1)

    def change_color(self, color):
        self.canvas.itemconfig(self.item, outline=color, fill=color)
Example #11
0
    def __str__(self):
        #posição de cada célula no grid do canvas para montar a representaça do cubo
        cels_canvas = (3, 4, 5, 15, 17, 27, 28, 29, 36, 37, 38, 48, 50, 60, 61,
                       62, 39, 40, 41, 51, 53, 63, 64, 65, 75, 76, 77, 87, 89,
                       99, 100, 101, 42, 43, 44, 54, 56, 66, 67, 68, 45, 46,
                       47, 57, 59, 69, 70, 71)
        master = Tk()
        w = Canvas(master, width=280, height=220)
        for pos, id_quadrado in enumerate(self.config):
            w.create_rectangle(
                20 + (cels_canvas[pos] % 12) * 20,
                20 + (cels_canvas[pos] / 12) * 20,
                40 + (cels_canvas[pos] % 12) * 20,
                40 + (cels_canvas[pos] / 12) * 20,
                fill=['green', 'red', 'white', 'blue', 'orange',
                      'yellow'][id_quadrado / 8])
            w.create_text(30 + (cels_canvas[pos] % 12) * 20,
                          30 + (cels_canvas[pos] / 12) * 20,
                          text=str(id_quadrado))

        for fixo in [{
                'pos': 16,
                't': 'L',
                'c': 'green'
        }, {
                'pos': 49,
                't': 'F',
                'c': 'red'
        }, {
                'pos': 52,
                't': 'U',
                'c': 'white'
        }, {
                'pos': 55,
                't': 'B',
                'c': 'orange'
        }, {
                'pos': 88,
                't': 'R',
                'c': 'blue'
        }, {
                'pos': 58,
                't': 'D',
                'c': 'yellow'
        }]:
            w.create_rectangle(20 + (fixo['pos'] % 12) * 20,
                               20 + (fixo['pos'] / 12) * 20,
                               40 + (fixo['pos'] % 12) * 20,
                               40 + (fixo['pos'] / 12) * 20,
                               fill=fixo['c'])
            w.create_text(30 + (fixo['pos'] % 12) * 20,
                          30 + (fixo['pos'] / 12) * 20,
                          text=fixo['t'],
                          font=Font(weight='bold', size=11))
        w.pack()
        master.mainloop()
        return str(self.config)
	def initUI(self):

		self.parent.title("Colors") # is parent = the background frame?
		self.pack(fill=BOTH, expand=1) # what is pack, fill, and expand? 

		canvas = Canvas(self)
		canvas.create_rectangle(30, 10, 120, 80, outline="#fb0", fill="#fb0")
		canvas.create_rectangle(150, 10, 240, 80, outline="#05f", fill="#05f")
		canvas.pack(fill=BOTH, expand=1)
Example #13
0
    def initUI(self):

        self.parent.title("Colors")  # is parent = the background frame?
        self.pack(fill=BOTH, expand=1)  # what is pack, fill, and expand?

        canvas = Canvas(self)
        canvas.create_rectangle(30, 10, 120, 80, outline="#fb0", fill="#fb0")
        canvas.create_rectangle(150, 10, 240, 80, outline="#05f", fill="#05f")
        canvas.pack(fill=BOTH, expand=1)
Example #14
0
    def initUI(self):
        self.parent.title("Colours")
        self.pack(fill=BOTH, expand=1)

        canvas = Canvas(self)
        canvas.create_rectangle(30, 10, 120, 80, outline="#fb0", fill="#fb0")
        canvas.create_rectangle(150, 10, 240, 80, outline="#f50", fill="#f50")
        canvas.create_rectangle(270, 10, 370, 80, outline="#05f", fill="#05f")
        canvas.pack(fill=BOTH, expand=1)
Example #15
0
    def initUI(self):
        self.parent.title("Colours")
        self.pack(fill=BOTH, expand=1)

        canvas = Canvas(self)
        canvas.create_rectangle(30, 10, 120, 80, outline="#fb0", fill="#fb0")
        canvas.create_rectangle(150, 10, 240, 80, outline="#f50", fill="#f50")
        canvas.create_rectangle(270, 10, 370, 80, outline="#05f", fill="#05f")
        canvas.pack(fill=BOTH, expand=1)
Example #16
0
def main():
    root = Tk()
    root.title('Layout Test')

    container = Canvas(root, width=600, height=400)
    container.create_rectangle(0, 0, 600, 400, fill='light grey')
    container.pack()

    tests(container)

    root.mainloop()
Example #17
0
		def initUI(self):

			self.parent.title("Colors")        
			self.pack(fill=BOTH, expand=1)

			canvas = Canvas(self)

			#modify rectangle size based on how many colors there are
			rect_size = 700/float(len(color_list))

			for i in range(len(self.color_list)):
				canvas.create_rectangle(10+rect_size*i, 10, 10+rect_size*(i+1), 110, outline=self.color_list[i], fill=self.color_list[i])
			canvas.pack(fill=BOTH, expand=1)
Example #18
0
class OpticalBeamsGUI(Frame):
  
    def __init__(self, parent):
        Frame.__init__(self, parent)   
        self.parent = parent        
        self.r = []
        self.initUI()

    def beamCallbackLeft(self, msg):
        self.changeColor(msg.broken, 'l')

    def beamCallbackRight(self, msg):
        self.changeColor(msg.broken, 'r')
    
    def changeColor(self, broken, side='r'):
        colors = ['red' if b else 'blue' for b in broken]
        k = 4 if side=='l' else 0
        for i in range(len(colors)):
            self.canvas.itemconfigure(self.r[k+i], fill=colors[i])
            
    def initUI(self):
        self.parent.title("Opticl Beams")        
        self.pack(fill=BOTH, expand=1)
        self.canvas = Canvas(self)

        # Right
        self.canvas.create_text(200, 50, text='r_gripper', font=("Helvetica",30))
        # CH1
        self.r.append(self.canvas.create_rectangle(0, 100, 200, 300, fill="blue"))
        self.canvas.create_text(100, 200, text='CH1', font=("Helvetica",30))
        # CH2
        self.r.append(self.canvas.create_rectangle(200, 300, 400, 500, fill="blue"))
        self.canvas.create_text(300, 400, text='CH2', font=("Helvetica",30))
        # CH3
        self.r.append(self.canvas.create_rectangle(200, 100, 400, 300, fill="blue"))
        self.canvas.create_text(300, 200, text='CH3', font=("Helvetica",30))
        # CH4
        self.r.append(self.canvas.create_rectangle(0, 300, 200, 500, fill="blue"))
        self.canvas.create_text(100, 400, text='CH4', font=("Helvetica",30))

        # Left
        self.canvas.create_text(700, 50, text='l_gripper', font=("Helvetica",30))
        # CH1
        self.r.append(self.canvas.create_rectangle(500, 100, 700, 300, fill="blue"))
        self.canvas.create_text(600, 200, text='CH1', font=("Helvetica",30))
        # CH2
        self.r.append(self.canvas.create_rectangle(700, 300, 900, 500, fill="blue"))
        self.canvas.create_text(800, 400, text='CH2', font=("Helvetica",30))
        # CH3
        self.r.append(self.canvas.create_rectangle(700, 100, 900, 300, fill="blue"))
        self.canvas.create_text(800, 200, text='CH3', font=("Helvetica",30))
        # CH4
        self.r.append(self.canvas.create_rectangle(500, 300, 700, 500, fill="blue"))
        self.canvas.create_text(600, 400, text='CH4', font=("Helvetica",30))

        self.canvas.pack(fill=BOTH, expand=1)

    def start(self):
        self.sub1 = rospy.Subscriber(TOPIC_LEFT, OpticalBeams, self.beamCallbackLeft)
        self.sub2 = rospy.Subscriber(TOPIC_RIGHT, OpticalBeams, self.beamCallbackRight)
Example #19
0
    def initUI(self):
        self.parent.title("Shapes")
        self.pack(fill=BOTH, expand=1)

        canvas = Canvas(self)
        canvas.create_oval(10, 10, 80, 80, outline="green", fill="red", width=2)
        canvas.create_oval(110, 10, 210, 80, outline="green", fill="red", width=2)
        canvas.create_rectangle(230, 10, 290, 60, outline="green", fill="red", width=2)
        canvas.create_arc(30, 200, 90, 100, start=0, extent=210, outline="green", fill="red", width=2)

        points = [150, 100, 200, 120, 240, 180, 210, 200, 150, 150, 100, 200]
        canvas.create_polygon(points, outline="green", fill="red", width=2)

        canvas.pack(fill=BOTH, expand=1)
Example #20
0
def view_stack():
    inputstring = u2_entry.get()
    row, ste, sta, inp, act = process_input(inputstring)
    print inputstring

    show = Toplevel(master)
    show.title("Stack Implementation")
    show.geometry("%dx%d%+d%+d" % (1300, 1300, 0, 0))
    canvas = Canvas(show, width=2000, height=1000)
    canvas.grid(row=0, column=0)
    row = row - 1
    col = 4
    m, a = 10, 10
    n = 100
    b = 125

    for i in range(len(sta)):
        canvas.create_text(a + 60, b + 15, text=i + 1, font="Times 15 bold")
        canvas.create_text(a + 60 + 260,
                           b + 15,
                           text=sta[i],
                           font="Times 15 bold")
        canvas.create_text(a + 60 + 400,
                           b + 15,
                           text=inp[i],
                           font="Times 15 bold")
        canvas.create_text(a + 60 + 660,
                           b + 15,
                           text=act[i],
                           font="Times 15 bold")

        b = b + 30

    for i in range(0, row + 1):
        for j in range(0, col):
            print(m, n)

            canvas.create_rectangle(m, n, m + 200, n + 30)
            m = m + 200
        m = 10
        n = n + 30
    print ste, sta, inp, act
    canvas.create_text(65, 110, text="S.N.", font="Times 15 bold")
    canvas.create_text(285, 110, text="Stack", font="Times 15 bold")
    canvas.create_text(475, 110, text="Input", font="Times 15 bold")
    canvas.create_text(665, 110, text="Action", font="Times 15 bold")

    show.geometry("%dx%d%+d%+d" % (1300, 800, 0, 0))
Example #21
0
def get_canvas():
    """ Creates a Tkinter canvas. """

    from Tkinter import Tk, Canvas, BOTH

    root = Tk()
    root.title('LED bot simulator')
    root.geometry("%sx%s" % (screen_width, screen_height))

    canvas = Canvas(root)
    canvas.pack(fill=BOTH, expand=1)
    canvas.create_rectangle(
        0, 0, screen_width, screen_height, outline="#000", fill="#000"
    )

    return canvas
Example #22
0
class canvasInterface(interfaceScreen):
    def __init__(self,master,width,height):
        interfaceScreen.__init__(self)
        self.canvas = Canvas(master, width=width, height=height,bg='white')
        self.canvas.grid(row=0,column=1)

    """
    ---------------Interfaz con objeto dibujante---------------------
    """

    def deleteFromCanvas(self,id):
        self.canvas.delete(id)
        pass

    def create_rectangle(self,x1, y1, x2, y2,*arg,**kargs):
        return self.canvas.create_rectangle(x1, y1, x2, y2,*arg,**kargs)
        pass

    def create_line(self,x1, y1, x2,  y2, *args,**kwargs):
        return self.canvas.create_line(x1, y1, x2,  y2, *args,**kwargs)

    def create_text(self,x1, y1,*args,**kargs):
        return self.canvas.create_text(x1, y1,*args,**kargs)

    def scan_mark(self,x,y):
        self.canvas.scan_mark(x, y)
    def scan_dragto(self,x, y, *args,**kwargs):
        self.canvas.scan_dragto(x, y, *args,**kwargs)

    def winfo_height(self):
        return self.canvas.winfo_height()
    def winfo_width(self):
        return self.canvas.winfo_width()
Example #23
0
def main():
    root = Tk()
    # w, h = root.winfo_screenwidth(), root.winfo_screenheight()
    w, h = 960, 540
    # get value from arduino
    # ser = serial.Serial('/dev/tty.usbserial', 9600)
    pos = 0
    root.overrideredirect(1)
    root.focus_set()
    root.bind("<Escape>", lambda e: e.widget.quit())
    root.geometry("%dx%d+300+300" % (w, h))
    canvas = Canvas(root, width=w, height=h, background="black")
    rect0 = canvas.create_rectangle(w/2-75, h/2-20, w/2+75, h/2+20, fill="#05f", outline="#05f")
    rect1 = canvas.create_rectangle(w/2-20, h/2-75, w/2+20, h/2+75, fill="#05f", outline="#05f")
    canvas.pack() 
    
    while (True):
        # gets angle and moves accordingly
        # pos = ser.readline()
        canvas.move(rect0, 1, 0)
        canvas.move(rect1, 1, 0)
        root.update()
        root.after(30)
      
    app = App(root)
    time.sleep(0.5)
    root.mainloop()  
Example #24
0
class Animation:
    def __init__(self):
        root = Tk()
        self.canvas = Canvas(root, height=500, width=500)
        self.canvas.pack()

        self.canvas.create_rectangle(0, 0, 500, 500, fill="#0D4566", outline="#0D4566")  # space
        self.venus = Planet(250, 150, self.canvas, "red")
        self.earth = Planet(250, 100, self.canvas, "green")
        self.sun = Planet(250, 250, self.canvas, "yellow")

        self.start = time.time()
        self.ticks = 0
        self.done = False
        self.timer()
        root.mainloop()

    def rotate_body(self, body, amount):
        theta = math.degrees(amount)

        x = body.x - 250
        y = body.y - 250

        x, y = x * math.cos(theta) - y * math.sin(theta), x * math.sin(theta) + y * math.cos(theta)

        x += 250
        y += 250

        body.move_to(x, y)

        self.canvas.update()

    def timer(self):
        if self.done:
            print "Done after %2.2f seconds!" % (time.time() - self.start)
            return
        self.rotate_body(self.earth, math.pi / 36000 * 13.0)
        self.rotate_body(self.venus, math.pi / 36000 * 8.0)

        self.ticks += 1
        if self.ticks % 2 == 0:
            self.canvas.create_line(self.earth.x, self.earth.y, self.venus.x, self.venus.y, fill="white")
        if self.ticks > 1250:
            self.done = True

        self.canvas.after(5, self.timer)
Example #25
0
class PRMViewer(object):
    def __init__(self, width=500, height=500, title='PRM', background='tan'):
        tk = Tk()
        tk.withdraw()
        top = Toplevel(tk)
        top.wm_title(title)
        top.protocol('WM_DELETE_WINDOW', top.destroy)
        self.width = width
        self.height = height
        self.canvas = Canvas(top, width=self.width, height=self.height, background=background)
        self.canvas.pack()

    def pixel_from_point(self, point):
        (x, y) = point
        # return (int(x*self.width), int(self.height - y*self.height))
        return (x * self.width, self.height - y * self.height)

    def draw_point(self, point, radius=5):
        (x, y) = self.pixel_from_point(point)
        self.canvas.create_oval(x - radius, y - radius, x + radius, y + radius, fill='black')

    def draw_line(self, segment):
        (point1, point2) = segment
        (x1, y1) = self.pixel_from_point(point1)
        (x2, y2) = self.pixel_from_point(point2)
        self.canvas.create_line(x1, y1, x2, y2, fill='black', width=2)

    def draw_arrow(self, point1, point2):
        (x1, y1) = self.pixel_from_point(point1)
        (x2, y2) = self.pixel_from_point(point2)
        self.canvas.create_line(x1, y1, x2, y2, fill='black', width=2, arrow=LAST)

    def draw_rectangle(self, box, width=2, color='brown'):
        (point1, point2) = box
        (x1, y1) = self.pixel_from_point(point1)
        (x2, y2) = self.pixel_from_point(point2)
        self.canvas.create_rectangle(x1, y1, x2, y2, fill=color, width=width)

    def draw_circle(self, center, radius, width=2, color='black'):
        (x1, y1) = self.pixel_from_point(np.array(center) - radius * np.ones(2))
        (x2, y2) = self.pixel_from_point(np.array(center) + radius * np.ones(2))
        self.canvas.create_oval(x1, y1, x2, y2, outline='black', fill=color, width=width)

    def clear(self):
        self.canvas.delete('all')
Example #26
0
 def __draw_continuous_view(self, min_val, max_val, scheme, m_unit_string,
                            n_classes):
     """
     :param min_val:
     :param max_val:
     :param scheme:
     :param m_unit_string:
     :param n_classes:
     :return:
     """
     is_width_longer = self._width > self._height
     start_x, start_y, x_pos, y_pos = 0, 0, 0, 0
     val_range = (max_val - min_val) / n_classes
     if is_width_longer:
         y_pos = int(self._height * 0.2)
         start_x = int(self._width * 0.25)
         square_side1 = int(0.2 * self._height)
         square_side2 = int((self._width / 2) / n_classes)
     else:
         x_pos = int(self._width * 0.2)
         start_y = int(self._height * 0.25)
         square_side1 = int((self._height / 2) / n_classes)
         square_side2 = int(0.2 * self._width)
     for i in xrange(n_classes):
         color = View.calculate_color(min_val, max_val, n_classes,
                                      val_range * i + 1, scheme)
         if is_width_longer:
             x_pos = start_x + (i * square_side2)
         else:
             y_pos = start_y + (i * square_side2)
         Canvas.create_rectangle(self,
                                 x_pos,
                                 y_pos,
                                 x_pos + square_side1,
                                 y_pos + square_side2,
                                 fill=color)
     text = str(float(min)) + m_unit_string + " - " + str(
         float(max)) + m_unit_string
     if is_width_longer:
         x = int(self._width / 2)
         y = int(self._height * 0.7)
     else:
         x = int(self._width * 0.7)
         y = int(self._height / 2)
     Canvas.create_text(self, x, y, text=text)
Example #27
0
class Application(object):
    def __init__(self, root, grid_size):
        root.title("Diffusion-Limited Aggregation")
        self.cell_size = WINDOW / grid_size
        self.grid = Grid(grid_size)
        self.canvas = Canvas(root, width=WINDOW, height=WINDOW)
        self.canvas.create_rectangle(0, 0, WINDOW, WINDOW, fill=BACKGROUND)
        self.canvas.pack()
        self.colorizer = Colorizer()

    def fill(self, x, y, color):
        x *= self.cell_size
        y *= self.cell_size
        self.canvas.create_rectangle(x,
                                     y,
                                     x + self.cell_size,
                                     y + self.cell_size,
                                     fill=color)
        self.canvas.update()

    def mark(self, speck, color):
        grid = speck.grid
        grid[speck.x, speck.y] = True
        self.fill(speck.x, speck.y, color)

    def evolve(self):
        # Fill in center cell.
        self.mark(Speck(self.grid, (self.grid.size / 2, self.grid.size / 2)),
                  self.colorizer.next())

        # Fill until the edge.
        number = 0
        while True:
            speck = Speck(self.grid)
            self.fill(speck.x, speck.y, "red")
            while speck.on_grid() and not speck.stuck():
                speck.move()
            if speck.on_grid():
                print "%d,+%d" % (number, speck.steps)
                self.mark(speck, self.colorizer.next())
                if speck.on_edge():
                    break
            else:
                print "%d,-%d" % (number, speck.steps)
            number += 1
    def show_window(self):
        root = Tk()
        canvas = Canvas(root, width=WIDTH, height=HEIGHT)

        self._arrange(self.page_sets, Rect(2, 2, WIDTH, HEIGHT), False)
        # self._adjust_line(self.page_sets)


        for page_set in self.page_sets:
            page = page_set[0]
            if page.rect:
                canvas.create_rectangle(page.rect.x, page.rect.y, page.rect.x + page.rect.width,
                                        page.rect.y + page.rect.height,
                                        outline="#555")
                canvas.create_text(page.rect.x + page.rect.width / 2, page.rect.y + 10,
                                   text=str(page.priority))
        canvas.pack()
        root.mainloop()
Example #29
0
 def _draw_fuel_view(self):
     """
     :return:
     """
     if self.__fuel_model is not None:
         side = self.__square_side
         for i in xrange(self.__n_rows):
             for j in xrange(self.__n_cols):
                 x = self.__start_x + j * side
                 y = self.__start_y + i * side
                 rbg_color = self._fuel_color_map[self.__fuel_model[i][j]]
                 hex_color = View.convert_rbg_triplet_hexadecimal(rbg_color)
                 Canvas.create_rectangle(self,
                                         x,
                                         y,
                                         x + side,
                                         y + side,
                                         fill=hex_color)
Example #30
0
    def draw_heights(self):
        """Draw grid of height values on window.

        Heights are shown as squares, with greyscale colors becoming brighter for greater heights.

        """
        canvas = Canvas(self)
        for x in range(self.terrain.width):
            for y in range(self.terrain.length):
                x_pos = x * Terrain2D.SQUARE_SIDE
                y_pos = y * Terrain2D.SQUARE_SIDE
                color = int(self.terrain[x, y] * 15)
                hex_color = "#" + "0123456789abcdef"[color] * 3
                canvas.create_rectangle(x_pos, y_pos,
                                        x_pos + Terrain2D.SQUARE_SIDE,
                                        y_pos + Terrain2D.SQUARE_SIDE,
                                        outline=hex_color, fill=hex_color)
        canvas.pack(fill=BOTH, expand=1)
Example #31
0
class LayoutTest(object):
    def __init__(self):
        root = Tk()
        root.title('Layout Test')

        self.container = Canvas(root, width=600, height=400)
        self.container.create_rectangle(0, 0, 600, 400, fill='light grey')
        self.container.pack()

        self.tests()

        root.mainloop()

    # Definiting Test cases here

    def tests(self):
        # Invoking test cases here
        pass
Example #32
0
class Application(object):

    def __init__(self, root, grid_size):
        root.title("Diffusion-Limited Aggregation")
        self.cell_size = WINDOW / grid_size
        self.grid = Grid(grid_size)
        self.canvas = Canvas(root, width=WINDOW, height=WINDOW)
        self.canvas.create_rectangle(0, 0, WINDOW, WINDOW, fill=BACKGROUND)
        self.canvas.pack()
        self.colorizer = Colorizer()

    def fill(self, x, y, color):
        x *= self.cell_size
        y *= self.cell_size
        self.canvas.create_rectangle(x, y,
                                     x + self.cell_size, y + self.cell_size,
                                     fill=color)
        self.canvas.update()

    def mark(self, speck, color):
        grid = speck.grid
        grid[speck.x, speck.y] = True
        self.fill(speck.x, speck.y, color)

    def evolve(self):
        # Fill in center cell.
        self.mark(Speck(self.grid, (self.grid.size/2, self.grid.size/2)),
                  self.colorizer.next())

        # Fill until the edge.
        number = 0
        while True:
            speck = Speck(self.grid)
            self.fill(speck.x, speck.y, "red")
            while speck.on_grid() and not speck.stuck():
                speck.move()
            if speck.on_grid():
                print "%d,+%d" % (number, speck.steps)
                self.mark(speck, self.colorizer.next())
                if speck.on_edge():
                    break
            else:
                print "%d,-%d" % (number, speck.steps)
            number += 1
Example #33
0
 def _draw_fuel_view(self):
     """
     :return:
     """
     is_width_longer = self._width > self._height
     start_x, start_y, x_pos, y_pos = 0, 0, 0, 0
     text_x_pos, text_y_pos = 0, 0
     half_n_fuels, x_leap = 0, 0
     n_fuels = len(self.__fuel_types)
     trim = 2
     if is_width_longer:
         start_y = int(self._height * 0.1)
         start_x = int(self._width * 0.1)
         square_side = int(0.2 * self._height)
         half_n_fuels = n_fuels / 2
         x_leap = (self._width - (2 * start_x)) / half_n_fuels
     else:
         x_pos = int(self._width * 0.1)
         start_y = int(self._height * 0.1)
         square_side = int(0.2 * self._width)
         text_x_pos = x_pos + square_side + trim
     for i in xrange(n_fuels):
         decimal_color = self._fuel_color_map[self.__fuel_types[i]]
         hex_color = View.convert_rbg_triplet_hexadecimal(decimal_color)
         fuel_name = self.__fuel_name_map[self.__fuel_types[i]]
         if is_width_longer:
             x_pos = start_x + ((i % half_n_fuels) * x_leap)
             y_pos = start_y + ((i / half_n_fuels) * (square_side + trim))
             text_x_pos = x_pos + square_side + trim
             text_y_pos = y_pos + square_side
         else:
             y_pos = start_y + (i * (square_side + trim))
             text_y_pos = y_pos + square_side
         Canvas.create_rectangle(self,
                                 x_pos,
                                 y_pos,
                                 x_pos + square_side,
                                 y_pos + square_side,
                                 fill=hex_color)
         Canvas.create_text(self,
                            text_x_pos,
                            text_y_pos,
                            anchor=SW,
                            text=fuel_name)
Example #34
0
def get_canvas():
    """ Creates a Tkinter canvas. """

    from Tkinter import Tk, Canvas, BOTH

    root = Tk()
    root.title('LED bot simulator')
    root.geometry("%sx%s" % (screen_width, screen_height))

    canvas = Canvas(root)
    canvas.pack(fill=BOTH, expand=1)
    canvas.create_rectangle(0,
                            0,
                            screen_width,
                            screen_height,
                            outline="#000",
                            fill="#000")

    return canvas
Example #35
0
class Grid(object):
    cell_size = 5

    def __init__(self):
        master = Tk()
        self.canvas = Canvas(master, width=800, height=600, background='black')
        self.canvas.pack()
        self.columns = int(self.canvas['width']) / self.cell_size
        self.rows = int(self.canvas['height']) / self.cell_size

    def put(self, x, y, tags=None):
        self.canvas.create_rectangle(x * self.cell_size,
                                     y*self.cell_size,
                                     x * self.cell_size + self.cell_size,
                                     y*self.cell_size + self.cell_size, 
                                     fill="white", outline="white", tags=tags)

    def move(self, tags, dx, dy):
        self.canvas.move(tags, dx*self.cell_size, dy*self.cell_size)
Example #36
0
class Display(Frame):
    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.canvas = None
        self.buffer = {}
        self.pixels = {}
        self.pack()
        self.init_display()

    def init_display(self):
        self.canvas = Canvas(self.master,
                             width=DISPLAY_W,
                             height=DISPLAY_H,
                             bg='white')
        self.canvas.pack()

        for x in range(PIXELS_X):
            for y in range(PIXELS_Y):
                pixel_x = ((PIXEL_W + PIXEL_SPACING) * x) + BORDER
                pixel_y = ((PIXEL_H + PIXEL_SPACING) * y) + BORDER
                self.buffer[(x, y)] = [0, 0, 0]
                self.pixels[(x, y)] = self.canvas.create_rectangle(
                    pixel_x,
                    pixel_y,
                    pixel_x + PIXEL_W,
                    pixel_y + PIXEL_H,
                    fill='black',
                    width=0)

    def set_pixel(self, x, y, r, g, b):
        self.buffer[(x, y)] = [r, g, b]

    def clear():
        # Clear the display
        for x in range(8):
            for x in range(8):
                self.set_pixel(x, y, 0, 0, 0)
                self.show()

    def show_q(self, pixels):
        x = 0
        for idx, pixel in enumerate(pixels):
            x = idx % 8
            y = int(idx / 8)
            self.canvas.itemconfigure(self.pixels[(x, y)], fill='#' + pixel)
            x += 1

    def show(self):
        for position, colour in self.buffer.iteritems():
            pixel = self.pixels[position]
            r = hex(colour[0])[2:].zfill(2)
            g = hex(colour[1])[2:].zfill(2)
            b = hex(colour[2])[2:].zfill(2)
            self.canvas.itemconfigure(pixel, fill='#' + r + g + b)
    def draw_heights(self):
        """Draw grid of height values on window.

        Heights are shown as squares, with greyscale colors becoming brighter for greater heights.

        """
        canvas = Canvas(self)
        for x in range(self.terrain.width):
            for y in range(self.terrain.length):
                x_pos = x * Terrain2D.SQUARE_SIDE
                y_pos = y * Terrain2D.SQUARE_SIDE
                color = int(self.terrain[x, y] * 15)
                hex_color = "#" + "0123456789abcdef"[color] * 3
                canvas.create_rectangle(x_pos,
                                        y_pos,
                                        x_pos + Terrain2D.SQUARE_SIDE,
                                        y_pos + Terrain2D.SQUARE_SIDE,
                                        outline=hex_color,
                                        fill=hex_color)
        canvas.pack(fill=BOTH, expand=1)
    def initUI(self):
        self.parent.title("Drawing Window")
        self.style = Style()
        self.style.theme_use("default")
        self.pack(fill=BOTH, expand=True)

        frameL = Frame(self, relief=RAISED, borderwidth=2)
        frameL.pack(fill=BOTH, expand=True)
        lbMax = Label(frameL, text="Maximum Arrangment", width=25)
        lbMax.pack(side=TOP, padx=5, pady=5)
        canvas = Canvas(frameL)
        canvas.create_rectangle(30, 10, 120, 80, outline="#fff", fill="#fff")

        frameR = Frame(self, relief=RAISED, borderwidth=2)
        frameR.pack(fill=BOTH, expand=True)
        lbMin = Label(frameR, text="Minimum Arrangment", width=25)
        lbMin.pack(side=TOP, padx=5, pady=5)

        quitButton = Button(self, text="Quit", command=self.quit)
        quitButton.pack(side=RIGHT, padx=10, pady=10)
Example #39
0
    def initUI(self):
        self.parent.title("Drawing Window")
        self.style = Style()
        self.style.theme_use("default")
        self.pack(fill=BOTH, expand=True)

        frameL = Frame(self, relief=RAISED, borderwidth=2)
        frameL.pack(fill=BOTH, expand=True)
        lbMax = Label(frameL, text="Maximum Arrangment", width=25)
        lbMax.pack(side=TOP, padx=5, pady=5)
        canvas = Canvas(frameL)
        canvas.create_rectangle(30, 10, 120, 80, outline="#fff", fill="#fff")

        frameR = Frame(self, relief=RAISED, borderwidth=2)
        frameR.pack(fill=BOTH, expand=True)
        lbMin = Label(frameR, text="Minimum Arrangment", width=25)
        lbMin.pack(side=TOP, padx=5, pady=5)

        quitButton = Button(self, text="Quit", command=self.quit)
        quitButton.pack(side=RIGHT, padx=10, pady=10)
Example #40
0
	def setup(self):
		self.parent.title(self.TITLE)
		self.pack(fill=BOTH, expand=1)
		canvas = Canvas(self)
		canvas.create_rectangle(self.ORIGIN_X, self.ORIGIN_Y, 
			self.ORIGIN_X + self.BLOCK_W, 
			self.ORIGIN_Y + self.BLOCK_H,
			fill=self.ORIGIN_FILL)
		canvas.create_line(0, self.ORIGIN_Y + (self.BLOCK_H/2),
			self.ORIGIN_X, self.ORIGIN_Y + (self.BLOCK_H/2),
			fill=self.ORIGIN_FILL,
			width=3.0)
		self.counter = canvas.create_text(
			self.COUNTER_X, 
			self.COUNTER_Y,
			anchor=NW)
		canvas.pack(fill=BOTH, expand=1)
		self.canvas = canvas
		self.addHonestNode()
		self.after(self.DELAY, self.update)
Example #41
0
    def initUI(self):

        self.parent.title("Shapes")
        self.pack(fill=BOTH, expand=1)

        canvas = Canvas(self)
        canvas.create_oval(10,
                           10,
                           80,
                           80,
                           outline="gray",
                           fill="gray",
                           width=2)
        canvas.create_oval(110,
                           10,
                           210,
                           80,
                           outline="gray",
                           fill="gray",
                           width=2)
        canvas.create_rectangle(230,
                                10,
                                290,
                                60,
                                outline="gray",
                                fill="gray",
                                width=2)
        canvas.create_arc(30,
                          200,
                          90,
                          100,
                          start=0,
                          extent=210,
                          outline="gray",
                          fill="gray",
                          width=2)

        points = [150, 100, 200, 120, 240, 180, 210, 200, 150, 150, 100, 200]
        canvas.create_polygon(points, outline='gray', fill='gray', width=2)

        canvas.pack(fill=BOTH, expand=1)
Example #42
0
class Display:
    def __init__(self, fps=FPS, width=WIDTH, height=HEIGHT,
        board_offset_bottom=BOARD_OFFSET_BOTTOM,
        board_width=BOARD_WIDTH,
        board_height=BOARD_HEIGHT):
        self.root=Tk()
        self.root.protocol("WM_DELETE_WINDOW", self.root.destroy)
        self.width = width
        self.height = height
        self.canvas=Canvas(self.root, bg="black",width=width,height=height)
        self.board_width = board_width
        self.board_height = board_height
        self.board_offset_bottom = board_offset_bottom
        self.canvas.pack()
        self.fps = fps
        self.controllers = []
        #For reset
        self.root.bind("<space>", lambda e:self.reset_all())
        self.root.bind("<Escape>", lambda e:self.root.destroy())
    def run(self):
        self.root.after(1000//self.fps, self.loop)
        try:
            self.root.mainloop()
        except KeyboardInterrupt:
            self.root.destroy()
    def loop(self):
        actions = [controller.get_action(self.model) for controller in self.controllers]
        self.model.update(1./self.fps, actions)
        self.draw()
        self.root.after(1000//self.fps, self.loop)
    def draw(self):
        self.canvas.delete('all')
        self.board = self.canvas.create_rectangle(
            self.model.x()-self.board_width/2,
            self.board_offset_bottom+self.height-self.board_height,
            self.model.x()+self.board_width/2,
            self.board_offset_bottom+self.height, fill="green")
        self.pendulum = self.canvas.create_line(
            self.model.x(),
            self.board_offset_bottom+self.height-self.board_height,
            self.model.x()+self.model.arm_length*math.sin(self.model.alpha()),
            self.board_offset_bottom+self.height-self.board_height-self.model.arm_length*math.cos(self.model.alpha()),
            fill="blue", width=20)
    def attach_model(self, model):
        self.model = model
        self.draw()
    def attach_controller(self, controller):
        self.controllers.append(controller)
    def reset_all(self):
        self.model.randomize()
Example #43
0
class SimulationStrip(Strip):
    def __init__(self, length, row_length, led_size=DEFAULT_LED_SIZE):
        super(SimulationStrip, self).__init__(length)
        led_window = Tk()
        led_window.title('LED Simulator')
        MARGIN = 5
        led_size = min(
            (led_window.winfo_screenwidth() - 2 * MARGIN) / row_length,
            led_size)
        num_rows = math.ceil(length / row_length)
        height = num_rows * led_size + (1 + num_rows) * MARGIN
        width = led_size * row_length + 2 * MARGIN
        self.canvas = Canvas(led_window, width=width, height=height)
        self.canvas.pack()
        self.leds = [] * length
        self.leds = [
            self.create_rectangle(i, row_length, led_size, MARGIN)
            for i in xrange(length)
        ]
        self.canvas.update()

    def show(self):
        for i in xrange(self.length):
            color = '#%02x%02x%02x' % tuple([(255 * c) / MAX_BRIGHTNESS
                                             for c in self[i]])
            self.canvas.itemconfigure(self.leds[i], fill=color)
        self.canvas.update()
        time.sleep(SHOW_SLEEP_TIME)

    def create_rectangle(self, index, row_length, led_size, margin):
        #x0
        if (index / row_length) % 2 == 0:
            x0 = margin + (index % row_length) * led_size
        else:
            x0 = margin + (row_length - (index % row_length) - 1) * led_size

        #y0
        y0 = margin + (led_size + margin) * (index / row_length)

        #x1
        if (index / row_length) % 2 == 0:
            x1 = margin + ((index % row_length) + 1) * led_size
        else:
            x1 = margin + (row_length - (index % row_length)) * led_size

        #y1
        y1 = margin + (led_size + margin) * (index / row_length) + led_size

        return self.canvas.create_rectangle(x0, y0, x1, y1)
Example #44
0
class DrawGrid(Frame):
    def __init__(self, parent, langton_ant):
        Frame.__init__(self, parent)
        self.parent = parent
        self.pack(fill=BOTH, expand=1)

        self.title = self.parent.title()

        self.rows = 101
        self.columns = 82
        self.cell_width = 6
        self.cell_height = 6

        self.canvas = Canvas(self, width=self.cell_width * self.columns, height=self.cell_height * self.rows,
                             borderwidth=0, highlightthickness=0)
        self.canvas.pack(side="top", fill="both", expand="true")

        self.rect = {}
        for column in range(self.columns):
            for row in range(self.rows):
                x1 = column * self.cell_width
                y1 = row * self.cell_height
                x2 = x1 + self.cell_width
                y2 = y1 + self.cell_height
                self.rect[row, column] = self.canvas.create_rectangle(x1, y1, x2, y2, fill="white", tags="rect",
                                                                      outline="gray")

        self.langton_ant = langton_ant
        self.draw_result(300)

    def draw_result(self, delay, step=0):
        """
        draw the grid and refresh
        """
        self.parent.title(self.title+" step: " + str(step))
        self.canvas.itemconfig("rect", fill="white")

        data = np.matrix(self.langton_ant.grid)
        nonzero_idx = data.nonzero()
        # dealing living cells (non zero matrix)
        for row,col in zip(nonzero_idx[0], nonzero_idx[1]):
            item_id = self.rect[row, col]
            self.canvas.itemconfig(item_id, fill="black")

        print_out_file(len(nonzero_idx[0]), "w" if step==0 else "a")
        self.langton_ant.next()
        self.after(delay, lambda: self.draw_result(delay, step+1))
class CaCanvas(Frame):
    def __init__(self, root, ca_width, ca_height, x_max, y_max):
        Frame.__init__(self, root)
        self.x_max = x_max
        self.y_max = y_max
        self.canvas = Canvas(self,
                             width=ca_width,
                             height=ca_height,
                             bg='white')
        self.canvas.pack()
        self.cell = [[None for x in range(x_max)] for y in range(y_max)]
        self.cell_count = [[0 for x in range(x_max)] for y in range(y_max)]
        self.x_scale = ca_width / x_max
        self.y_scale = ca_height / y_max
        self.create_grid()

    def create_grid(self):
        for x in range(self.x_max):
            for y in range(self.y_max):
                self.cell[x][y] = self.canvas.create_rectangle(
                    (x * self.x_scale, y * self.y_scale,
                     (x + 1) * self.x_scale, (y + 1) * self.y_scale),
                    outline='white',
                    fill='white')

    def set_on(self, x, y):
        self.canvas.itemconfig(self.cell[x][y], fill="black")
        self.cell_count[x][y] = 1

    def set_off(self, x, y):
        self.canvas.itemconfig(self.cell[x][y], fill="white")
        self.cell_count[x][y] = 0

    def count_cells(self):
        count = 0
        for x in range(self.x_max):
            for y in range(self.y_max):
                count += self.cell_count[x][y]
        return count

    def clear_cells(self):
        for x in range(self.x_max):
            for y in range(self.y_max):
                self.set_off(x, y)
Example #46
0
class SimulationStrip(Strip):
    def __init__(self, length, row_length, led_size=DEFAULT_LED_SIZE):
        super(SimulationStrip, self).__init__(length)
        led_window = Tk()
        led_window.title('LED Simulator')
        MARGIN = 5
        led_size = min((led_window.winfo_screenwidth() - 2 * MARGIN) / row_length, led_size)
        num_rows = math.ceil(length / row_length)
        height = num_rows * led_size + (1 + num_rows) * MARGIN
        width = led_size * row_length + 2 * MARGIN
        self.canvas = Canvas(led_window, width=width, height=height)
        self.canvas.pack()
        self.leds = [] * length
        self.leds = [self.create_rectangle(i, row_length, led_size, MARGIN) for i in xrange(length)]
        self.canvas.update()

    def show(self):
        for i in xrange(self.length):
            color = '#%02x%02x%02x' % tuple([(255 * c) / MAX_BRIGHTNESS for c in self[i]])
            self.canvas.itemconfigure(self.leds[i], fill=color)
        self.canvas.update()
        time.sleep(SHOW_SLEEP_TIME)

    def create_rectangle(self, index, row_length, led_size, margin):
        #x0
        if (index / row_length) % 2 == 0:
            x0 = margin + (index % row_length) * led_size
        else:
            x0 = margin + (row_length - (index % row_length) - 1) * led_size

        #y0
        y0 = margin + (led_size + margin) * (index / row_length)

        #x1
        if (index / row_length) % 2 == 0:
            x1 = margin + ((index % row_length) + 1) * led_size
        else:
            x1 = margin + (row_length - (index % row_length)) * led_size

        #y1
        y1 = margin + (led_size + margin) * (index / row_length) + led_size

        return self.canvas.create_rectangle(x0, y0, x1, y1)
Example #47
0
class App(Frame):
    """Tkinter App."""

    def __init__(self, parent, queue):
        """Init Tkinter app."""
        Frame.__init__(self, parent)
        self.parent = parent
        self.parent.wm_attributes("-type", "dialog")

        self.queue = queue
        self.initUI()
        self.worker()

    def initUI(self):
        """Init UI."""
        self.parent.title("PySnake")
        self.canvas = Canvas(self.parent, width=500, height=300, bg="black")
        self.canvas.pack()

        self.score = self.canvas.create_text(30, 270, anchor=W, fill="blue", text="Score: 0")
        self.food = self.canvas.create_rectangle(0, 0, 0, 0, fill="white")
        self.snake = self.canvas.create_line((0, 0), (0, 0), fill="green", width=10)

    def worker(self):
        try:
            while True:
                job = self.queue.get_nowait()
                if job.has_key("snake"):
                    # self.snake = self.canvas.create_line(*job['snake'], fill='green', width=10)
                    points = [x for point in job["snake"] for x in point]
                    self.canvas.coords(self.snake, *points)
                elif job.has_key("food"):
                    x, y = job["food"]
                    self.canvas.coords(self.food, (x - 5), (y - 5), (x + 5), (y + 5))
                elif job.has_key("score"):
                    self.canvas.itemconfigure(self.score, text="Score: {}".format(job["score"]))
                elif job.has_key("quit"):
                    self.parent.quit()
                self.queue.task_done()
        except Queue.Empty:
            pass
        self.after(50, self.worker)
Example #48
0
class App(Frame):
    """Tkinter App."""

    def __init__(self, parent, queue):
        """Init Tkinter app."""
        Frame.__init__(self, parent)
        self.parent = parent
        self.parent.wm_attributes('-type', 'dialog')

        self.queue = queue
        self.initUI()
        self.worker()

    def initUI(self):
        """Init UI."""
        self.parent.title('PySnake')
        self.canvas = Canvas(self.parent, width=500, height=300, bg='black')
        self.canvas.pack()

        self.score = self.canvas.create_text(30, 270, anchor=W, fill='blue', text='Score: 0')
        self.food = self.canvas.create_rectangle(0, 0, 0, 0, fill='white')
        self.snake = self.canvas.create_line((0, 0), (0, 0), fill='green', width=10)

    def worker(self):
        try:
            while True:
                job = self.queue.get_nowait()
                if job.has_key('snake'):
                    #self.snake = self.canvas.create_line(*job['snake'], fill='green', width=10)
                    points = [x for point in job['snake'] for x in point]
                    self.canvas.coords(self.snake, *points)
                elif job.has_key('food'):
                    x, y = job['food']
                    self.canvas.coords(self.food, (x - 5), (y - 5), (x + 5), (y + 5))
                elif job.has_key('score'):
                    self.canvas.itemconfigure(self.score, text='Score: {}'.format(job['score']))
                elif job.has_key('quit'):
                    self.parent.quit()
                self.queue.task_done()
        except Queue.Empty:
            pass
        self.after(50, self.worker)
Example #49
0
class SpectrumGraph(object):
    def __init__(self, root):
        # create bar graph
        self._canvas = Canvas(root,
                              width=CANVAS_WIDTH,
                              height=CANVAS_HEIGHT,
                              bg='black')
        self._canvas.pack()

        self._bars = []
        for pos in range(0, CANVAS_WIDTH, BAR_WIDTH):
            r = self._canvas.create_rectangle(pos,
                                              CANVAS_HEIGHT,
                                              pos + BAR_WIDTH,
                                              100,
                                              fill='white')
            self._bars.append(r)

    """
    Function set_bar_data(self, data)
    Takes a 1d signal of 2^N length, and averages it over the bars, then sets the data to the graph
    eg: an array a[1023:0:] -> a[63:0]
    """

    def set_bar_data(self, data):
        assert (len(data) % NUM_BARS == 0)
        stride = len(data) / NUM_BARS
        bars = np.mean(data.reshape(-1, stride),
                       axis=1)  # computes average for bars
        self._set_bars(bars)

    """
    Given a numpy array of length equal to the number of bars, we set each bar to that particular height
    """

    def _set_bars(self, bars):
        for i, pos in enumerate(range(0, CANVAS_WIDTH, BAR_WIDTH)):
            bar_height = min(CANVAS_HEIGHT, CANVAS_HEIGHT * bars[i])
            self._canvas.coords(self._bars[i], pos, CANVAS_HEIGHT,
                                pos + BAR_WIDTH, CANVAS_HEIGHT - bar_height)
class CaCanvas(Frame):
    def __init__(self,root,ca_width,ca_height,x_max,y_max):
        Frame.__init__(self,root)
        self.x_max = x_max
        self.y_max = y_max
        self.canvas = Canvas(self,width=ca_width,height=ca_height,bg='white')
        self.canvas.pack()
        self.cell = [[None for x in range(x_max)] for y in range(y_max)]
        self.cell_count = [[0 for x in range(x_max)] for y in range(y_max)]
        self.x_scale = ca_width/x_max
        self.y_scale = ca_height/y_max
        self.create_grid()
    
    def create_grid(self):
        for x in range(self.x_max):
            for y in range(self.y_max):
                self.cell[x][y] = self.canvas.create_rectangle((x*self.x_scale,y*self.y_scale,(x+1)*self.x_scale,(y+1)*self.y_scale),outline='white',fill='white')
                
    def set_on(self,x,y):
        self.canvas.itemconfig(self.cell[x][y], fill="black")
        self.cell_count[x][y]=1

        
    def set_off(self,x,y):
        self.canvas.itemconfig(self.cell[x][y], fill="white")
        self.cell_count[x][y]=0

    def count_cells(self):
        count = 0
        for x in range(self.x_max):
            for y in range(self.y_max): 
                count+=self.cell_count[x][y]
        return count
        
    def clear_cells(self):
        for x in range(self.x_max):
            for y in range(self.y_max): 
                self.set_off(x,y)
    def draw(self):
        self.parent.title("Layout")        
        self.pack(fill=BOTH, expand=1)

        x_size = self.grid[0]*scale_c+margin
        y_size = self.grid[1]*scale_c+margin
        canvas = Canvas(self,width=800,height=450)
        canvas.create_rectangle(margin+x_origin, margin+y_origin, \
            (x_size+x_origin), (y_size+y_origin), \
            tags="Obj", outline="#fff", fill="#fff")
        for gate in self.gates:
            fill_t = "#f10"
            if (re.match(r"DFF",gate[0])):
                fill_t = "#05f"
            bry = y_size - gate[2]*scale_c+y_origin
            tly = bry - scale_c
            brx = gate[1]*scale_c+margin+x_origin
            tlx = brx + scale_c                
            canvas.create_rectangle(tlx, tly, \
                brx, bry, \
                tags="Obj",outline=fill_t, fill=fill_t)
           # canvas.create_text(brx+scale_c/10,(bry+tly)/2, \
           #     anchor=W,font="Helvetica",\
           #     text=gate[0])
        for port in self.ports:
            y_fix_port = 0; 
            x_fix_port = 0; 
            if (port[2] >= self.grid[1]-1):
                y_fix_port = -scale_c+y_origin
            if (port[2] <= 1):
                y_fix_port = scale_c+y_origin
            if(port[1] >= self.grid[0]-1):
                x_fix_port = scale_c+x_origin
            if(port[1] <= 1):
                x_fix_port = -scale_c+x_origin
            bry = y_size - port[2]*scale_c+y_fix_port
            tly = bry - scale_c 
            brx = port[1]*scale_c+margin+x_fix_port
            tlx = brx + scale_c                
            canvas.create_rectangle(tlx, tly, brx, bry,
                tags="Obj",outline="black", fill="green")
            canvas.create_text(brx+scale_c/10,(bry+tly)/2, \
                anchor=W,font="Helvetica",\
                text=port[0])           
        canvas.pack(fill=BOTH, expand=1)
Example #52
0
    def initUI(self):
      
        self.parent.title("Colors")        
        self.pack(fill=BOTH, expand=1)

        canvas = Canvas(self)
        #We create the Canvas widget.
        canvas.create_rectangle(30, 10, 120, 80, 
            outline="#fb0", fill="#fb0")
        canvas.create_rectangle(150, 10, 240, 80, 
            outline="#f50", fill="#f50")
        canvas.create_rectangle(270, 10, 370, 80, 
            outline="#05f", fill="#05f")
        #The create_rectangle() creates a rectangle item on the canvas. 
        #The first four parameters are the x and y coordinates of the two bounding points. 
        #The top-left and the bottom-right. 
        #With the outline parameter we control the colour of the outline of the rectangle. 
        #Likewise, the fill parameter provides a colour for the inside of the rectangle.
        canvas.pack(fill=BOTH, expand=1)
Example #53
0
class ContinuousTMPViewer(object):
    def __init__(self,
                 suction_height,
                 regions,
                 tl_x=0,
                 tl_y=0,
                 width=500,
                 height=150,
                 title='Grid',
                 background='tan'):
        self.tk = Tk()
        # tk.geometry('%dx%d+%d+%d'%(width, height, 100, 0))
        self.tk.withdraw()
        self.top = Toplevel(self.tk)
        self.top.wm_title(title)
        self.top.protocol('WM_DELETE_WINDOW', self.top.destroy)

        self.suction_height = suction_height
        self.regions = regions
        self.tl_x = tl_x
        self.tl_y = tl_y
        self.width = width
        self.height = height
        self.canvas = Canvas(self.top,
                             width=self.width,
                             height=self.height,
                             background=background)
        self.canvas.pack()
        # self.center()
        self.move_frame(self.tl_x, self.tl_y)

        max_width = max(
            map(get_width,
                regions.values()))  # Really should take width of max minus min
        self.dist_to_pixel = (self.width - 2 * PIXEL_BUFFER
                              ) / max_width  # Maintains aspect ratio
        self.dist_width = self.width / self.dist_to_pixel
        self.dist_height = self.height / self.dist_to_pixel
        self.ground_height = self.height - self.dist_to_pixel * ENV_HEIGHT
        self.robot_dist = self.dist_height / 2.

        self.robot = []
        self.blocks = []
        self.holding = None
        self.environment = []
        self.draw_environment()

    def center(self):
        self.top.update_idletasks()
        w = self.top.winfo_screenwidth()
        h = self.top.winfo_screenheight()
        size = tuple(
            int(_) for _ in self.top.geometry().split('+')[0].split('x'))
        x = w / 2 - size[0] / 2
        y = h / 2 - size[1] / 2
        self.top.geometry("%dx%d+%d+%d" % (size + (x, y)))

    def move_frame(self, x, y):
        self.top.update_idletasks()
        size = tuple(
            int(_) for _ in self.top.geometry().split('+')[0].split('x'))
        self.top.geometry("%dx%d+%d+%d" % (size + (x, y)))

    def scale_x(self, x):  # x \in [-self.dist_width/2, self.dist_width/2]
        return self.dist_to_pixel * (x + self.dist_width / 2.)

    def scale_y(self, y):  # y \in [0, self.dist_height]
        return self.ground_height - self.dist_to_pixel * y

    def draw_block(self, x, y, width, height, name='', color='blue'):
        self.blocks.extend([
            self.canvas.create_rectangle(self.scale_x(x - width / 2.),
                                         self.scale_y(y),
                                         self.scale_x(x + width / 2.),
                                         self.scale_y(y + height),
                                         fill=color,
                                         outline='black',
                                         width=2),
            self.canvas.create_text(self.scale_x(x),
                                    self.scale_y(y + height / 2),
                                    text=name),
        ])

    # def draw_holding(self, x, width, height, color='blue'):
    #     self.holding = self.canvas.create_rectangle(self.scale_x(x - width / 2.),
    #                                                 self.scale_y(self.robot_dist - SUCTION_HEIGHT / 2 - height),
    #                                                 self.scale_x(x + width / 2.),
    #                                                 self.scale_y(self.robot_dist - SUCTION_HEIGHT / 2),
    #                                                 fill=color, outline='black', width=2)

    def draw_region(self, region, name='', color='red'):
        x1, x2 = map(self.scale_x, region)
        y1, y2 = self.ground_height, self.height
        self.environment.extend([
            self.canvas.create_rectangle(x1,
                                         y1,
                                         x2,
                                         y2,
                                         fill=color,
                                         outline='black',
                                         width=2),
            self.canvas.create_text((x1 + x2) / 2, (y1 + y2) / 2, text=name),
        ])

    def draw_environment(self):
        # TODO: automatically draw in order
        self.environment = []
        for name, region in sorted(self.regions.items(),
                                   key=lambda pair: get_width(pair[1]),
                                   reverse=True):
            self.draw_region(region, name=name, color=name)

    def draw_robot(
        self,
        x,
        y,
        color='yellow'
    ):  # TODO - could also visualize as top grasps instead of side grasps
        #y = self.robot_dist
        self.robot = [
            self.canvas.create_rectangle(
                self.scale_x(x - SUCTION_WIDTH / 2.),
                self.scale_y(y - self.suction_height / 2.),
                self.scale_x(x + SUCTION_WIDTH / 2.),
                self.scale_y(y + self.suction_height / 2.),
                fill=color,
                outline='black',
                width=2),
            self.canvas.create_rectangle(
                self.scale_x(x - STEM_WIDTH / 2.),
                self.scale_y(y + self.suction_height / 2.),
                self.scale_x(x + STEM_WIDTH / 2.),
                self.scale_y(y + self.suction_height / 2. + STEM_HEIGHT),
                fill=color,
                outline='black',
                width=2),
        ]

    def clear_state(self):
        for block in self.blocks:
            self.canvas.delete(block)
        for part in self.robot:
            self.canvas.delete(part)
        if self.holding is not None:
            self.canvas.delete(self.holding)

    def clear_all(self):
        self.canvas.delete('all')

    def save(self, filename):
        # TODO: screen recording based on location like I did before
        # TODO: only works on windows
        # self.canvas.postscript(file='%s.ps'%filename, colormode='color')
        #from PIL import ImageGrab
        try:
            import pyscreenshot as ImageGrab
        except ImportError:
            return None
        x, y = self.top.winfo_x(), 2 * self.top.winfo_y()
        width, height = self.top.winfo_width(), self.top.winfo_height(
        )  # winfo_width, winfo_reqheight
        path = filename + '.png'
        ImageGrab.grab((x, y, x + width, y + height)).save(path)
        return path
Example #54
0
class PhraseEditor(HasTraits):
    """A graphical editor for musical phrases."""

    phrase = Instance(Phrase)
    """The phrase which is edited."""

    selected_point = Instance(Point)
    """The point that is currently moved around."""

    use_grid = Bool
    """Whether added points shall be snapped to a grid."""

    grid_resolution = Range(2,64, 16)
    """The resolution of the grid."""

    point_handle_size = Int(4)
    """The size of the handles used to move points around."""

    def __init__(self, toplevel, phrase, **kwargs):
        """
        Initializes a PhraseEditor.

        @param toplevel: the Tk Toplevel window
        @param phrase: the phrase to be edited
        """

        # The Tk Toplevel object to which the editor will be attached 
        self.toplevel = toplevel

        control_frame = Frame(self.toplevel)
        control_frame.pack(side=TOP)

        title_frame = Frame(control_frame, padx=8)
        title_frame.pack(side=LEFT)

        Label(title_frame, text="Title").pack(side=LEFT)

        self.title_entry_manager = EntryManager(
            title_frame, self, 'phrase.name'
        )
        self.title_entry_manager.entry.pack(side=LEFT)

        grid_frame = Frame(control_frame, padx=8)
        grid_frame.pack(side=LEFT)

        self.grid_checkbutton_manager = CheckbuttonManager(
            grid_frame, self, 'use_grid', text="Grid"
        )
        self.grid_checkbutton_manager.checkbutton.pack(side=LEFT)

        Label(grid_frame, text="Resolution").pack(side=LEFT)

        self.grid_resolution_spinbox_manager = SpinboxManager(
            grid_frame, self, 'grid_resolution',
        )
        self.grid_resolution_spinbox_manager.spinbox.pack(side=LEFT)

        steps_frame = Frame(control_frame, padx=8)
        steps_frame.pack(side=LEFT)

        Label(steps_frame, text="Steps").pack(side=LEFT)

        self.steps_spinbox_manager = SpinboxManager(
            steps_frame, self, 'phrase.steps',
        )
        self.steps_spinbox_manager.spinbox.pack(side=LEFT)

        transpose_frame = Frame(control_frame, padx=8)
        transpose_frame.pack(side=LEFT)

        Label(transpose_frame, text="Transpose").pack(side=LEFT)

        self.transpose_spinbox_manager = SpinboxManager(
            transpose_frame, self, 'phrase.transpose',
        )
        self.transpose_spinbox_manager.spinbox.pack(side=LEFT)

        self.v_point_type = StringVar()
        self.v_point_type.set('Note')

        OptionMenu(
            control_frame, self.v_point_type, 'Note', 'Rest',
        ).pack(side=LEFT)

        self.canvas = Canvas(self.toplevel, width=600, height=400)
        self.canvas.pack(side=BOTTOM)

        # Maps a Point to the ID of its handle, which is a rectangle on the
        # canvas. 
        self._point_handles = {}

        # Maps a tuple of two Points to the ID of the line connecting them on
        # the canvas.
        self._point_lines = {}

        # Maps a Point to the line to its next Point that is currently played.
        self._playing_lines = {}

        # A set of dotted lines marking the grid on the canvas.
        self._grid_lines = set()

        super(PhraseEditor, self).__init__(
            phrase=phrase, use_grid=True, **kwargs
        )

        def find_point(x,y):
            """
            @return: the point at the specified position on the canvas.
            """
            s = self.point_handle_size
            for point in self.phrase.points:
                px,py = point.pos
                if px-s <= x <= px+s and py-s <= y <= py+s:
                    return point
            return None

        def snap_to_grid(x,y):
            """
            Rounds the given coordinates to the grid defined by
            L{PhraseEditor.grid_resolution}.
            """
            res = self.grid_resolution
            return round(x/float(res))*res, round(y/float(res))*res

        def button_pressed(event):
            """
            When the left mouse button is pressed over a point, it becomes the
            L{PhraseEditor.selected_point}, which can be moved around by
            L{button_motion()}.

            If there is no point under the mouse pointer, a new point is
            appended to the L{Phrase}.
            """
            x = self.canvas.canvasx(event.x)
            y = self.canvas.canvasy(event.y)
            point = find_point(x,y)
            if point is None:
                if self.use_grid:
                    x,y = snap_to_grid(x,y)
                point = Point(
                    pos=(int(x),int(y)),
                    type=self.v_point_type.get(),
                )
                self.phrase.points.append(point)
            self.selected_point = point
        self.canvas.bind('<Button-1>', button_pressed)

        def button_motion(event):
            """
            If the mouse is moved while the left or miffle mouse button is held
            down and a point is selected, this point is moved to the current
            mouse pointer position.
            """
            if self.selected_point is None:
                return
            x = self.canvas.canvasx(event.x)
            y = self.canvas.canvasy(event.y)
            if self.use_grid:
                x,y = snap_to_grid(x,y)
            canvas_config = self.canvas.config()
            canvas_width = int(canvas_config['width'][-1])
            canvas_height = int(canvas_config['height'][-1])
            self.selected_point.pos = (
                min(canvas_width, max(0, int(x))),
                min(canvas_height, max(0, int(y)))
            )
        self.canvas.bind('<B1-Motion>', button_motion)
        self.canvas.bind('<B2-Motion>', button_motion)

        def button_released(event):
            """
            When releasing the left or middle mouse button, the currently
            selected point is deselected.
            """
            self.selected_point = None
        self.canvas.bind('<ButtonRelease-1>', button_released)
        self.canvas.bind('<ButtonRelease-2>', button_released)

        def right_button_pressed(event):
            """
            Pressing the right mouse button over a point removes it from the
            L{Phrase}.
            """
            x = self.canvas.canvasx(event.x)
            y = self.canvas.canvasy(event.y)
            point = find_point(x,y)
            if point is not None:
                self.phrase.points.remove(point)
        self.canvas.bind('<Button-3>', right_button_pressed)

        def middle_button_pressed(event):
            if self.selected_point is not None:
                return
            x = self.canvas.canvasx(event.x)
            y = self.canvas.canvasy(event.y)
            point = find_point(x,y)
            if point is None:
                return
            new_point = Point(pos=point.pos, type=self.v_point_type.get())
            self.phrase.points.insert(
                self.phrase.points.index(point)+1,
                new_point
            )
            self.selected_point = new_point
        self.canvas.bind('<Button-2>', middle_button_pressed)

    def close(self):
        """
        Closes the editor, destroying its Toplevel window.
        """
        #del self.phrase
        #del self.selected_point
        #del self._point_handles
        #del self._point_lines
        #del self._playing_lines
        self.toplevel.destroy()

    def _add_point_handle(self, point):
        """
        Adds a point handle for the given point to the canvas.
        """
        s = self.point_handle_size
        px, py = point.pos
        self._point_handles[point] = self.canvas.create_rectangle(
            px-s,py-s, px+s,py+s,
        )

    def _remove_point_handle(self, point):
        """
        Removes the point handle for the given point.
        """
        self.canvas.delete(self._point_handles[point])
        del self._point_handles[point]

    def _add_point_line(self, point1, point2):
        """
        Adds a line between two points on the canvas.
        """
        px1, py1 = point1.pos
        px2, py2 = point2.pos
        self._point_lines[
            (point1, point2)
        ] = self.canvas.create_line(
            px1,py1, px2,py2,
            dash=[2,2] if point2.type == 'Rest' else None
        )

    def _remove_point_line(self, point1, point2):
        """
        Removes the line between two given points.
        """
        px1, py1 = point1.pos
        px2, py2 = point2.pos
        self.canvas.delete(self._point_lines[(point1, point2)])
        del self._point_lines[(point1, point2)]

    def _remove_point_lines(self):
        for points, line in self._point_lines.iteritems():
            self.canvas.delete(line)
        self._point_lines = {}

    def _remove_point_handles(self):
        for point, handle in self._point_handles.iteritems():
            self.canvas.delete(handle)
        self._point_handles = {}

    @on_trait_change('phrase, phrase:points')
    def _points_changed(self, obj, name, old, new):
        if self.phrase is None:
            return
        self._remove_point_handles()
        self._remove_point_lines()
        points = self.phrase.points
        for i, point in enumerate(points):
            self._add_point_handle(point)
            if i > 0:
                self._add_point_line(points[i-1], point)

    @on_trait_change('phrase:points:pos')
    def _point_pos_changed(self, point, name, old, new):
        """
        When a point's position changes, its handle and lines to its
        surrounding points are redefined.
        """
        self._remove_point_handle(point)
        self._add_point_handle(point)
        points = self.phrase.points
        assert point in points
        i = points.index(point)
        if i > 0:
            source_point = points[i-1]
            self._remove_point_line(source_point, point)
            self._add_point_line(source_point, point)
        if i < len(points)-1:
            target_point = points[i+1]
            self._remove_point_line(point, target_point)
            self._add_point_line(point, target_point)

    @on_trait_change('phrase.name')
    def _phrase_name_changed(self):
        """
        When the name of the phrase changes, the window title is update.
        """
        if self.phrase is None:
            return
        self.toplevel.title("Phrase: %s" % self.phrase.name)

    def add_playing_point(self, point, color):
        if point in self._playing_lines:
            self.remove_playing_point(point, color)
        if point not in self.phrase.points:
            return
        px,py, px2,py2 = self.phrase.get_line(point)
        self._playing_lines[point] = self.canvas.create_line(
            px,py, px2,py2, fill=color, width=2.0,
            dash=[2,2] if point.type == 'Rest' else None
        )

    def remove_playing_point(self, point, color):
        if point not in self._playing_lines:
            return
        self.canvas.delete(self._playing_lines[point])
        del self._playing_lines[point]

    @on_trait_change('use_grid, grid_resolution')
    def _grid_changed(self):
        """
        Draws a grid if L{PhraseEditor.use_grid} is True, otherwise removes it.
        """
        for rect in self._grid_lines:
            self.canvas.delete(rect)
        self._grid_lines.clear()
        if self.use_grid:
            config = self.canvas.config()
            w = int(config['width'][-1])
            h = int(config['height'][-1])
            res = self.grid_resolution
            for y in range(0, h, res):
                self._grid_lines.add(self.canvas.create_line(
                    0,y, w,y, dash=[1,res-1], fill="#666666"
                ))
Example #55
0
                canv.delete(rects[i][j])
                rects[i][j]=canv.create_rectangle(w*i/n, h*j/n, w*(i+1)/n, h*(j+1)/n, fill="lightblue", outline="lightblue")
            else: new_grid[i][j]=grid[i][j]
    for i in range(len(new_grid)):
        for j in range(len(new_grid[i])):
            grid[i][j]=new_grid[i][j]
    canv.after(20, tick, grid, rects)
w, h = 600, 600
n, m = 20, 20
paused = True
grid=[]; new_grid=[]; rects=[]
root = Tk()
canv = Canvas(root, width=w, height=h, bg="white")
##for i in range(n+1):canv.create_line(w*i/n,0,w*i/n,h, fill = "lightblue")
##for i in range(m+1):canv.create_line(0,h*i/m,w,h*i/m, fill = "lightblue")
for i in range(n):
    grid.append([])
    rects.append([])
    for j in range(m):
        grid[i].append(0)
        rects[i].append(canv.create_rectangle(w*i/n, h*j/n, w*(i+1)/n, h*(j+1)/n, fill="white", outline="lightblue"))

for (i, j) in [(0, 1), (0, 2), (1, 0), (1, 1), (2, 1)]:
    grid[i][j]=1
    canv.delete(rects[i][j])
    rects[i][j]=canv.create_rectangle(w*i/n, h*j/n, w*(i+1)/n, h*(j+1)/n, fill="lightblue", outline="lightblue")

canv.pack()
root.bind('<1>', lambda e: left(e, grid, rects))
root.bind('<space>', begin)
root.mainloop()
Example #56
0
    yp = 0.7 * h - 0.7 * h * y / 100.0
    canvas.coords(ship, w / 4, yp)

    if y >= 0.0:
        canvas.after(1, tick)


root = Tk()
canvas = Canvas(root, width=w, height=h, bg='black')
canvas.pack()

img1 = Image.open('earthrise.jpg').resize((w, h))
pmg1 = ImageTk.PhotoImage(img1)
canvas.create_image(w / 2, h / 2, image=pmg1)

img2 = Image.open('eagle.jpg').resize((200, 200))
pmg2 = ImageTk.PhotoImage(img2)
ship = canvas.create_image(w / 4, 0, image=pmg2)

canvas.create_rectangle(w / 4 - 150,
                        int(0.5 + 0.7 * h) + 100,
                        w / 4 + 150,
                        int(0.5 + 0.7 * h) + 125,
                        outline='green',
                        fill='green')

print t, y, vy

canvas.after(1000, tick)
root.mainloop()
Example #57
0
class main:
   
    def __init__(self,master):
        self.frame = Frame(master)
        self.frame.pack(fill="both", expand=True)
        self.canvas = Canvas(self.frame, width=300, height=300)
        self.canvas.pack(fill="both", expand=True)
        self.label=Label(self.frame, text='Tic Tac Toe Game', height=6, bg='black', fg='blue')
        self.label.pack(fill="both", expand=True)
        self.frameb=Frame(self.frame)
        self.frameb.pack(fill="both", expand=True)
        self.Start1=Button(self.frameb, text='Click here to start\ndouble player', height=4, command=self.start1,bg='white', fg='purple')
        self.Start1.pack(fill="both", expand=True, side=RIGHT)
        self.Start2=Button(self.frameb, text='Click here to start\nsingle player', height=4, command=self.start2,bg='purple', fg='white')
        self.Start2.pack(fill="both", expand=True, side=LEFT)     
        self._board()

    def start1(self):
        self.canvas.delete(ALL)
        self.label['text']=('Tic Tac Toe Game')
        self.canvas.bind("<ButtonPress-1>", self.sgplayer)  
        self._board()
        self.TTT=[[0,0,0],[0,0,0],[0,0,0]]
        self.i=0
        self.j=False

    def start2(self):
        self.canvas.delete(ALL)
        self.label['text']=('Tic Tac Toe Game')
        self.canvas.bind("<ButtonPress-1>", self.dgplayer)  
        self._board()
        self.TTT=[[0,0,0],[0,0,0],[0,0,0]]
        self.i=0
        self.j=False
        self.trigger=False

    def end(self):
        self.canvas.unbind("<ButtonPress-1>")
        self.j=True
        
    
    def _board(self):
        self.canvas.create_rectangle(0,0,300,300, outline="black")
        self.canvas.create_rectangle(100,300,200,0, outline="black")
        self.canvas.create_rectangle(0,100,300,200, outline="black")
        
    def sgplayer(self,event):
        for k in range(0,300,100):
            for j in range(0,300,100):
                if event.x in range(k,k+100) and event.y in range(j,j+100):
                    if self.canvas.find_enclosed(k,j,k+100,j+100)==():
                        if self.i%2==0:
                            X=(2*k+100)/2
                            Y=(2*j+100)/2
                            X1=int(k/100)
                            Y1=int(j/100)
                            self.canvas.create_oval( X+25, Y+25, X-25, Y-25, width=4, outline="black")
                            self.TTT[Y1][X1]+=1
                            self.i+=1
                        else:                         
                            X=(2*k+100)/2
                            Y=(2*j+100)/2
                            X1=int(k/100)
                            Y1=int(j/100)
                            self.canvas. create_line( X+20, Y+20, X-20, Y-20, width=4, fill="black")
                            self.canvas. create_line( X-20, Y+20, X+20, Y-20, width=4, fill="black")
                            self.TTT[Y1][X1]+=9
                            self.i+=1
        self.check()

    def dgplayer(self,event):
        for k in range(0,300,100):
            for j in range(0,300,100):
                if self.i%2==0:
                    if event.x in range(k,k+100) and event.y in range(j,j+100):
                        if self.canvas.find_enclosed(k,j,k+100,j+100)==():
                            X=(2*k+100)/2
                            Y=(2*j+100)/2
                            X1=int(k/100)
                            Y1=int(j/100)
                            self.canvas.create_oval( X+25, Y+25, X-25, Y-25, width=4, outline="black")
                            self.TTT[Y1][X1]+=1
                            self.i+=1
                            self.check()
                            self.trigger=False                           
                else:
                    print(self.i)
                    self.check()
                    print("checked")
                    self.AIcheck()
                    print("AIchecked")
                    self.trigger=False
                    
                    

                        
                        
    def check(self):
        #horizontal check
        for i in range(0,3):
            if sum(self.TTT[i])==27:
                self.label['text']=('2nd player wins!')
                self.end()
            if sum(self.TTT[i])==3:
                self.label['text']=('1st player wins!')
                self.end()
        #vertical check
        #the matrix below transposes self.TTT so that it could use the sum fucntion again
        self.ttt=[[row[i] for row in self.TTT] for i in range(3)]
        for i in range(0,3):            
            if sum(self.ttt[i])==27:
                self.label['text']=('2nd player wins!')
                self.end()
            if sum(self.ttt[i])==3:
                self.label['text']=('1st player wins!')
                self.end()
        #check for diagonal wins
        if self.TTT[1][1]==9:
            if self.TTT[0][0]==self.TTT[1][1] and self.TTT[2][2]==self.TTT[1][1] :
                self.label['text']=('2nd player wins!')
                self.end()
            if self.TTT[0][2]==self.TTT[1][1] and self.TTT[2][0]==self.TTT[1][1] :
                self.label['text']=('2nd player wins!')
                self.end()
        if self.TTT[1][1]==1:
            if self.TTT[0][0]==self.TTT[1][1] and self.TTT[2][2]==self.TTT[1][1] :
                self.label['text']=('1st player wins!')
                self.end()
            if self.TTT[0][2]==self.TTT[1][1] and self.TTT[2][0]==self.TTT[1][1] :
                self.label['text']=('1st player wins!')
                self.end()
        #check for draws
        if self.j==False:
            a=0
            for i in range(0,3):
                a+= sum(self.TTT[i])
            if a==41:
                self.label['text']=("It's a pass!")
                self.end()

                
    def AIcheck(self):
        #This is built on the self.check function
        self.ttt=[[row[i] for row in self.TTT] for i in range(3)]
        #DEFENSE
        #this is the horizontal checklist    
        for h in range(0,3): 
            k=0
            j=0            
            if sum(self.TTT[h])==2:
                while k <3:
                    if k==h:
                        while j <3:
                            if self.trigger==False:
                                if self.TTT[k][j]==0:
                                    self.cross(j,k)
                                    break
                            j+=1
                    k+=1
        #this is the vertical checklist
        for h in range(0,3):
            k=0
            j=0
            if sum(self.ttt[h])==2:                        
                while k <3:
                    if k==h:
                        while j <3:
                            if self.trigger==False:
                                if self.ttt[k][j]==0:
                                    self.cross(k,j)
                                    break
                            j+=1
                    k+=1                    
        #this is the diagonal checklist
        if self.TTT[1][1]==1:
            if self.TTT[0][0]==1:
                if self.trigger==False:
                    if self.TTT[2][2]==0:
                        self.cross(2,2)
            if self.TTT[0][2]==1:
                if self.trigger==False:
                    if self.TTT[2][0]==0:
                        self.cross(0,2)
            if self.TTT[2][0]==1:
                if self.trigger==False:
                    if self.TTT[0][2]==0:
                        self.cross(2,0)
            if self.TTT[2][2]==1:
                if self.trigger==False:
                    if self.TTT[0][0]==0:
                        self.cross(0,0)
                        
        if self.TTT[1][1]==0:
            if self.trigger==False:
                self.cross(1,1)
                self.trigger=True
        else:
            if self.trigger==False:
                self.randmove()

    def cross(self, k, j):
        # k is the x coords
        # j is the y coords
        X=(200*k+100)/2
        Y=(200*j+100)/2
        X1=int(k)
        Y1=int(j)
        self.canvas. create_line( X+20, Y+20, X-20, Y-20, width=4, fill="black")
        self.canvas. create_line( X-20, Y+20, X+20, Y-20, width=4, fill="black")
        self.TTT[Y1][X1]+=9
        self.check()
        self.i+=1
        self.trigger=True

                

    def randmove(self):
        while True:
            k=(randint(0,2))
            j=(randint(0,2))
            if self.TTT[j][k]==0:
                X=(200*k+100)/2
                Y=(200*j+100)/2
                self.canvas. create_line( X+20, Y+20, X-20, Y-20, width=4, fill="black")
                self.canvas. create_line( X-20, Y+20, X+20, Y-20, width=4, fill="black")
                self.TTT[j][k]+=9
                self.check()
                self.i+=1
                self.trigger=True
                break
            else:
                k=(randint(0,2))*100
                j=(randint(0,2))*100
Example #58
0
class main:

	def __init__ (self):
		self.app = Tk()
		self.app.title('Tic Tac Toe')
		#self.app.resizable(width=False, height=False)
		#width and hight of window
		w = 900
		h = 1100
		#width and hight of screen
		ws = self.app.winfo_screenwidth()
		hs = self.app.winfo_screenheight()
		#calculate position
		x = ws/2 - w/2
		y = hs/2 - h/2
		#place window -> pramaters(visina, dolzina, pozicija x, pozicija y)
		self.app.geometry("%dx%d+%d+%d" % (w,h, x, y))

		#======================================
		self.frame = Frame() #main frame
		self.frame.pack(fill = 'both', expand = True)
		self.label = Label(self.frame, text	= 'Tic Tac Toe', height = 4, bg = 'white', fg = 'blue')
		self.label.pack(fill='both', expand = True)
		#self.label2 = Label(self.frame, text	= 'here', height = 2, bg = 'white', fg = 'blue') odkomentiri samo za develop-------------
		#self.label2.pack(fill='both', expand = True)
		self.canvas = Canvas(self.frame, width = 900, height = 900)
		self.canvas.pack(fill = 'both', expand = True)
		self.framepod = Frame(self.frame)#sub frame
		self.framepod.pack(fill = 'both', expand = True)
		self.Single = Button(self.framepod, text = 'Start single player', height = 4, command = self.startsingle, bg = 'white', fg = 'blue')
		self.Single.pack(fill='both', expand = True, side=RIGHT)
		self.Multi = Button(self.framepod, text = 'Start double player', height = 4, command = self.double, bg = 'white', fg = 'blue')
		self.Multi.pack(fill='both', expand = True, side=RIGHT)
		self.board = AI()
		self.draw()

	def double(self): 
		#cleans the all simbols from canvas
		self.canvas.delete(ALL)
		self.label['text'] = ('Tic Tac Toe Game')
		self.canvas.bind("<ButtonPress-1>", self.place)
		self.draw() #---------------------------------------
		self.table=[[-1,-1,-1],[-1,-1,-1],[-1,-1,-1]]
		self.c=0 #counter
		self.e=False #flag for end game

	def draw(self): #draws the outline lines
		self.canvas.create_rectangle(0,0,900,900, outline='black')
		self.canvas.create_rectangle(300,900,600,0, outline='black')
		self.canvas.create_rectangle(0,300,900,600, outline='black')

	def place(self, event):
		for i in range(0,900,300):
			for j in range(0,900,300):
				if event.x in range(i,i+300) and event.y in range(j, j+300):
					if self.canvas.find_enclosed(i,j,i+300, j+300) == ():
						if self.c % 2 == 0:
							#calculate points to draw circle
							x=(2*i+300)/2
							y=(2*j+300)/2
							x2=int(i/300)
							y2=int(j/300)
							self.canvas.create_oval(x+75,y+75,x-75,y-75, width = 4, outline="blue")
							self.table[y2][x2] = 4
							self.c+=1
						else:
							#calculate points to draw cross
							x=(2*i+300)/2
							y=(2*j+300)/2
							x2=int(i/300)
							y2=int(j/300)
							self.canvas.create_line(x+60,y+60,x-60,y-60, width = 4, fill="red")
							self.canvas.create_line(x-60,y+60,x+60,y-60, width = 4, fill="red")
							self.table[y2][x2] = 1
							self.c+=1
		self.check() 


	def startsingle(self):
		self.canvas.delete(ALL)
		self.label['text'] = ('Tic Tac Toe Game')
		self.canvas.bind("<ButtonPress-1>", self.placeone)
		self.draw()
		self.board = AI()

	def placeone(self, event):
		player = 'X'
		for i in range(0,900,300):
			for j in range(0,900,300):
				if event.x in range(i,i+300) and event.y in range(j, j+300):
					if self.canvas.find_enclosed(i,j,i+300, j+300) == ():
						x=(2*i+300)/2
						y=(2*j+300)/2
						x2=int(i/300)
						y2=int(j/300)
						self.canvas.create_line(x+60,y+60,x-60,y-60, width = 4, fill="red")
						self.canvas.create_line(x-60,y+60,x+60,y-60, width = 4, fill="red")

						
						player_move = x2 + 3*y2 #spremeni
						self.board.make_move(player_move, player)
						
		if self.board.complete():
			self.label['text'] = (self.board.winner())
			self.canvas.unbind("ButtonPress-1")
			self.board = AI()
		elif self.board.winner() != None:
			self.label['text'] = (self.board.winner())
			self.canvas.unbind("ButtonPress-1")
			self.board = AI()
		else:
			player = self.board.get_enemy(player)
			computer_move = self.board.determine(self.board, player)
			self.board.make_move(computer_move, player)

			ti = computer_move % 3
			tj = computer_move / 3

			x=(600*ti+300)/2
			y=(600*tj+300)/2
			#self.label2['text'] = str(computer_move) + '  ti ' + str(ti) + ' tj ' + str(tj) + ' y ' + str(y) + ' x ' +str(x)
			self.canvas.create_oval(x+75,y+75,x-75,y-75, width = 4, outline="blue")
			
			if self.board.winner() != None:
				self.label['text'] = (self.board.winner())
				self.canvas.unbind("ButtonPress-1")
				self.board = AI()

 

	def check(self):
		#checks for win
		#horitontal
		for i in range(3):
			if sum(self.table[i])==3:
				self.label['text'] = ('X wins')
				self.end()
			if sum(self.table[i])==12:
				self.label['text'] = ('O wins')
				self.end()
		#vertical
		self.vs=[[row[i] for row in self.table] for i in range(3)]
		for i in range(3):
			if sum(self.vs[i])==3:
				self.label['text'] = ('X wins')
				self.end()
			if sum(self.vs[i])==12:
				self.label['text'] = ('O wins')
				self.end()
		#diagonals
		self.dig1=0
		self.dig2=0
		for i in range(3):
			self.dig1+=self.table[i][i]
		for i in range(3):
			self.dig2+=self.table[2-i][i]

		if self.dig1==3:
			self.label['text'] = ('X wins')
			self.end()
		if self.dig1==12:
			self.label['text'] = ('O wins')
			self.end()
		if self.dig2==3:
			self.label['text'] = ('X wins')
			self.end()
		if self.dig2==12:
			self.label['text'] = ('O wins')
			self.end()

		#draw
		if self.e==False:
			a=0
			for i in range(3):
				a+=sum(self.table[i])
			if a == 24: #5 *4 + 4 * 1 --> 5 circles and 4 crosses
				self.label['text'] = ('Draw')
				self.end()

	def end(self):
		self.canvas.unbind("<ButtonPress-1>")
		self.e=True

	def mainloop(self):
		self.app.mainloop()