def initUI(self): # Setting title as wordle self.parent.title("Wordle") self.pack(fill=BOTH, expand=1) #print "Inside Canvas", self.arg # Task 5 - Pad outside border by 50 pixels all around # Canvas with 50 pixels outside border canvas = Canvas(self, bd=50, bg = "white") # Two helper variables # for generating start position of a word # Task 6 - Random color for each word # Generating Random colors for each of the word for word, value in self.arg.items(): # Task 7 - Font size based on frequency of the words # Generating font size based on the frequency of the words! # Very simple logic # Could make it more complex but didn't do that! if value > 15: i = random.randrange(150,400, 70) j = random.randrange(150,600, 50) else: i = random.randrange(200,600, 27) j = random.randrange(100,600, 33) canvas.create_text(i, j, anchor=W, font=("times",(value*2)), text=word, fill=choice(COLORS)) canvas.pack(fill=BOTH, expand=1)
class ImageView(BaseView): def __init__(self, manager): self.viewname = 'imageview' BaseView.__init__(self, manager) def pack_view(self, *args, **kwargs): layout = kwargs.get('layout', 2) image_object = kwargs['image_object'] image_no = kwargs.get('image_no', None) left_frame = self.display_left(flexible=True) _display_idx = self.manager.get_display_index() _display_size = (self.config.DISPLAY_SIZE[_display_idx][0], self.config.DISPLAY_SIZE[_display_idx][1]) self.manager.log('display size', _display_size) self._imgtk = ImageTk.PhotoImage(image_object.resize(_display_size)) # # self.frame = Frame(self.master) # self.frame = Frame(self.master, bg='white', width=_display_size[0], height=_display_size[1]) # self.frame.grid_propagate(0) left_frame.config(bg='white', width=_display_size[0], height=_display_size[1]) self.canvas = Canvas(left_frame, width=_display_size[0], height=_display_size[1], bg='red') # self.canvas.grid_propagate(0) self.canvas.place(relx=0.5, rely=0.5, anchor=CENTER) self.canvas.create_image(2, 2, image=self._imgtk, anchor='nw') if image_no is not None: self.canvas.create_text(self._imgtk.width() * 0.9, self._imgtk.height() * 0.9, text="Image No: " + str(image_no), fill="white") if layout == 2: bottom_frame = self.display_bottom(True) self.add_next_action_btn(lambda: self.done()) self.display()
class gridDisplay(Frame): def __init__(self, parent, board): """ Initialize an instance of the board within the TKinter hierarchy. Draws the game grid and fills it in with the current state of the board as passed into it by the displayBoard method. Numbers part of the goal configuration are displayed in blue, the rest in black. """ Frame.__init__(self, parent) self.parent = parent self.board = board self.pack(fill=BOTH) self.canvas = Canvas(self, width = WIDTH, height = HEIGHT) self.canvas.pack(fill=BOTH, side=TOP) for i in xrange(4): color = "red" if (i == 0 or i == 3) else "gray" #Color the grid boundaries red. x0 = x1 = MARGIN + i * SIDE y0 = MARGIN y1 = HEIGHT - MARGIN self.canvas.create_line(x0, y0, x1, y1, fill=color) self.canvas.create_line(y0, x0, y1, x1, fill=color) for i in xrange(3): for j in xrange(3): answer = self.board[i][j] #Current state of board at i,j if answer != 0: x = MARGIN + j * SIDE + SIDE / 2 y = MARGIN + i * SIDE + SIDE / 2 original = goalConfiguration[i][j] #Goal state of board at i, j color = "blue" if answer == original else "black" #Number printed in blue if part of goal state, black if not. self.canvas.create_text(x, y, text=answer, tags="numbers", fill=color)
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("Lyrics") self.pack(fill=BOTH, expand=1) canvas = Canvas(self) canvas.create_text(20, 30, anchor=W, font="Purisa", text="Most relationships seem so transitory") canvas.create_text(20, 60, anchor=W, font="Purisa", text="They're good but not the permanent one") canvas.create_text(20, 130, anchor=W, font="Purisa", text="Who doesn't long for someone to hold") canvas.create_text(20, 160, anchor=W, font="Purisa", text="Who knows how to love without being told") canvas.create_text(20, 190, anchor=W, font="Purisa", text="Somebody tell me why I'm on my own") canvas.create_text(20, 220, anchor=W, font="Purisa", text="If there's a soulmate for everyone") canvas.pack(fill=BOTH, expand=1)
def xGC_skew(seq, window=1000, zoom=100, r=300, px=100, py=100): """Calculates and plots normal and accumulated GC skew (GRAPHICS !!!).""" from Tkinter import Scrollbar, Canvas, BOTTOM, BOTH, ALL, \ VERTICAL, HORIZONTAL, RIGHT, LEFT, X, Y yscroll = Scrollbar(orient=VERTICAL) xscroll = Scrollbar(orient=HORIZONTAL) canvas = Canvas(yscrollcommand=yscroll.set, xscrollcommand=xscroll.set, background='white') win = canvas.winfo_toplevel() win.geometry('700x700') yscroll.config(command=canvas.yview) xscroll.config(command=canvas.xview) yscroll.pack(side=RIGHT, fill=Y) xscroll.pack(side=BOTTOM, fill=X) canvas.pack(fill=BOTH, side=LEFT, expand=1) canvas.update() X0, Y0 = r + px, r + py x1, x2, y1, y2 = X0 - r, X0 + r, Y0 - r, Y0 + r ty = Y0 canvas.create_text(X0, ty, text='%s...%s (%d nt)' % (seq[:7], seq[-7:], len(seq))) ty += 20 canvas.create_text(X0, ty, text='GC %3.2f%%' % (GC(seq))) ty += 20 canvas.create_text(X0, ty, text='GC Skew', fill='blue') ty += 20 canvas.create_text(X0, ty, text='Accumulated GC Skew', fill='magenta') ty += 20 canvas.create_oval(x1, y1, x2, y2) acc = 0 start = 0 for gc in GC_skew(seq, window): r1 = r acc += gc # GC skew alpha = pi - (2*pi*start)/len(seq) r2 = r1 - gc*zoom x1 = X0 + r1 * sin(alpha) y1 = Y0 + r1 * cos(alpha) x2 = X0 + r2 * sin(alpha) y2 = Y0 + r2 * cos(alpha) canvas.create_line(x1, y1, x2, y2, fill='blue') # accumulated GC skew r1 = r - 50 r2 = r1 - acc x1 = X0 + r1 * sin(alpha) y1 = Y0 + r1 * cos(alpha) x2 = X0 + r2 * sin(alpha) y2 = Y0 + r2 * cos(alpha) canvas.create_line(x1, y1, x2, y2, fill='magenta') canvas.update() start += window canvas.configure(scrollregion=canvas.bbox(ALL))
def xGC_skew(seq, window = 1000, zoom = 100, r = 300, px = 100, py = 100): """Calculates and plots normal and accumulated GC skew (GRAPHICS !!!).""" from Tkinter import Scrollbar, Canvas, BOTTOM, BOTH, ALL, \ VERTICAL, HORIZONTAL, RIGHT, LEFT, X, Y yscroll = Scrollbar(orient = VERTICAL) xscroll = Scrollbar(orient = HORIZONTAL) canvas = Canvas(yscrollcommand = yscroll.set, xscrollcommand = xscroll.set, background = 'white') win = canvas.winfo_toplevel() win.geometry('700x700') yscroll.config(command = canvas.yview) xscroll.config(command = canvas.xview) yscroll.pack(side = RIGHT, fill = Y) xscroll.pack(side = BOTTOM, fill = X) canvas.pack(fill=BOTH, side = LEFT, expand = 1) canvas.update() X0, Y0 = r + px, r + py x1, x2, y1, y2 = X0 - r, X0 + r, Y0 -r, Y0 + r ty = Y0 canvas.create_text(X0, ty, text = '%s...%s (%d nt)' % (seq[:7], seq[-7:], len(seq))) ty +=20 canvas.create_text(X0, ty, text = 'GC %3.2f%%' % (GC(seq))) ty +=20 canvas.create_text(X0, ty, text = 'GC Skew', fill = 'blue') ty +=20 canvas.create_text(X0, ty, text = 'Accumulated GC Skew', fill = 'magenta') ty +=20 canvas.create_oval(x1,y1, x2, y2) acc = 0 start = 0 for gc in GC_skew(seq, window): r1 = r acc+=gc # GC skew alpha = pi - (2*pi*start)/len(seq) r2 = r1 - gc*zoom x1 = X0 + r1 * sin(alpha) y1 = Y0 + r1 * cos(alpha) x2 = X0 + r2 * sin(alpha) y2 = Y0 + r2 * cos(alpha) canvas.create_line(x1,y1,x2,y2, fill = 'blue') # accumulated GC skew r1 = r - 50 r2 = r1 - acc x1 = X0 + r1 * sin(alpha) y1 = Y0 + r1 * cos(alpha) x2 = X0 + r2 * sin(alpha) y2 = Y0 + r2 * cos(alpha) canvas.create_line(x1,y1,x2,y2, fill = 'magenta') canvas.update() start += window canvas.configure(scrollregion = canvas.bbox(ALL))
def createScale(self): "Create a and return a new canvas with scale markers." height = float(self.gheight) width = 25 ymax = self.ymax scale = Canvas(self, width=width, height=height, background=self.bg) opts = {'fill': 'red'} # Draw scale line scale.create_line(width - 1, height, width - 1, 0, **opts) # Draw ticks and numbers for y in range(0, int(ymax + 1)): ypos = height * (1 - float(y) / ymax) scale.create_line(width, ypos, width - 10, ypos, **opts) scale.create_text(10, ypos, text=str(y), **opts) return scale
def createScale(self): "Create a and return a new canvas with scale markers." height = float(self.gheight) width = 25 ymax = self.ymax scale = Canvas(self, width=width, height=height, background=self.bg) opts = {"fill": "red"} # Draw scale line scale.create_line(width - 1, height, width - 1, 0, **opts) # Draw ticks and numbers for y in range(0, int(ymax + 1)): ypos = height * (1 - float(y) / ymax) scale.create_line(width, ypos, width - 10, ypos, **opts) scale.create_text(10, ypos, text=str(y), **opts) return scale
class StartFrame(Frame): """Class which controls start screen of spelling aid""" def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent #Create UI elements self.start_canvas = Canvas(self, width=600, height=250, bg="#FFFFFF") self.start_canvas.pack() buttonStart = Button(self, text="Start", width=10, command=self.start) buttonEdit = Button(self, text="Edit Lists", command=self.parent.show_editor) self.list_menu_var = StringVar(self) self.list_menu_var.set("Random List") self.start_canvas.create_window(300, 200, window=buttonStart) self.menu = self.start_canvas.create_window(300, 150) self.start_canvas.create_window(520, 230, window=buttonEdit) self.start_canvas.create_text(300, 100, font=("Helvetica", 25), text="Select a list:") self.update_list() self.update() def start(self): """Start the game with the selected list""" self.parent.start_game(self.selected_list) def update(self, event=None): """Change the current list to match selection""" list_name = self.list_menu_var.get() for word_list in self.parent.list_list: if word_list.name == list_name: self.selected_list = word_list def update_list(self): """Refreshes the list of lists""" list_menu = OptionMenu(self, self.list_menu_var, *self.parent.list_list, command=self.update) list_menu.configure(width=30) self.start_canvas.itemconfig(self.menu, window=list_menu) def welcomeMessage(self): """Show the welcome message""" self.start_canvas.create_text((10, 10), anchor=NW, text="Welcome, %s." %(self.parent.user.username), font=("Helvetica", 15))
class GUI(object): def __init__(self, world): self.ticks = 0 self.world = world self.width = world.width self.height = world.height self.root = Tk() self.root.title("Mars Explorer") window_x, window_y = self._compute_window_coords() self.root.geometry('%dx%d+%d+%d' % (self.width, self.height, window_x, window_y)) self.canvas = Canvas(self.root, width=self.width, height=self.height) self.canvas.pack() self.canvas.after(1, self._tick) def start(self): self.root.mainloop() def _tick(self): # Stop if done. if self.world.is_done(): return self.world.tick() self._draw() self.ticks += 1 self.canvas.after(1, self._tick) def _draw(self): self.canvas.delete('all') self.world.draw(self.canvas) for entity in self.world.entities: entity.draw(self.canvas) self.canvas.create_text(self.width - 20, 10, text=str(self.ticks)) self.canvas.create_text(self.width - 70, 30, text='Rocks in explorers: %d' % self.world.rocks_in_explorers()) self.canvas.create_text(self.width - 70, 50, text='Rocks delivered: %d' % self.world.rocks_collected) self.canvas.create_text(self.width - 55, 70, text='Total rocks: %d' % self.world.num_rocks) def _compute_window_coords(self): # http://stackoverflow.com/a/14912644/742501 screen_width = self.root.winfo_screenwidth() screen_height = self.root.winfo_screenheight() window_x = screen_width / 2 - self.width / 2 window_y = screen_height / 2 - self.height / 2 return window_x, window_y
class CoordsCanvas(object): def __init__(self, parent, **kwargs): self._canvas = Canvas(parent, **kwargs) self._canvas.pack(fill=BOTH, expand=YES) self._canvas.bind("<Double-Button-1>", self.on_double_click) self._canvas.bind("<Shift-Button-1>", self.on_shift_button_click) self._canvas.bind("<Control-Button-1>", self.on_ctrl_button_click) self._canvas.bind("<Alt-Button-1>", self.on_alt_button_click) self._canvas.bind("<Option-Button-1>", self.on_alt_button_click) self._canvas.bind("<Double-Button-1>", self.on_double_click) self._canvas.bind("<ButtonPress-1>", self.on_button_press) self._canvas.bind("<ButtonRelease-1>", self.on_button_release) self._event_receiver = None self._dragger = Dragger() def on_double_click(self, _): if hasattr(self._event_receiver, 'zoom_in'): self._event_receiver.zoom_in() def on_shift_button_click(self, _): if hasattr(self._event_receiver, 'zoom_out'): self._event_receiver.zoom_out() def on_ctrl_button_click(self, event): if hasattr(self._event_receiver, 'add'): self._event_receiver.add(event.x, event.y) def on_alt_button_click(self, event): if hasattr(self._event_receiver, 'remove'): self._event_receiver.remove(event.x, event.y) def on_button_press(self, event): self._dragger.start(event.x, event.y) def on_button_release(self, event): if hasattr(self._event_receiver, 'move'): self._dragger.drag_to( event.x, event.y, self._event_receiver.move) def create_circle(self, x, y, r, **kwargs): return self._canvas.create_oval(x-r, y-r, x+r, y+r, **kwargs) def create_text(self, x, y, **kwargs): return self._canvas.create_text(x, y, **kwargs) def get_width(self): return self._canvas.winfo_reqwidth() def get_height(self): return self._canvas.winfo_reqheight() def set_event_receiver(self, receiver): self._event_receiver = receiver def destroy(self, item): self._canvas.delete(item) def destroy_all(self): self._canvas.delete("all")
class bootWindow: def __init__(self, parent): logging.info("Host IP: " +get_ip()) self.screen = Canvas(parent, bg=black, height=480, width=320) self.screen.place(x=0,y=0) Testline = self.screen.create_line(160, 0, 160, 480, fill=red) Testline2 = self.screen.create_line(0, 240, 320, 240, fill=red) self.img = ImageTk.PhotoImage(Image.open("images/logo.PNG")) self.imglabel = Label(self.screen, image=self.img).place(x=160, y=150, anchor="center") self.text = self.screen.create_text(160,270 , text="Loading, Please wait...", fill=white, font=(textFont, 13)) self.p = ttk.Progressbar(self.screen, orient="horizontal", length=200, mode='determinate') self.p.place(x=160, y=300, anchor="center") # LOAD ALL THE STUFF!! parent.update() self.p.step(10) parent.update() #time.sleep(1) self.p.step(10) parent.update() #time.sleep(1) self.p.step(30) parent.update() time.sleep(1) self.screen.destroy() self.p.destroy() def hide(self): pass def show(self): pass def update(self): pass def __del__(self): pass
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()
def show_mol( mol): from Tkinter import Tk, Canvas, Frame app = Tk() app.title( "oasa") mainFrame = Frame( app) mainFrame.pack( fill='both', expand=1) paper = Canvas( mainFrame, width=640, height=480, background="white", closeenough=5) paper.pack() xmin, xmax, ymin, ymax = None,None,None,None for a in mol.vertices: if xmin == None or a.x < xmin: xmin = a.x if xmax == None or a.x > xmax: xmax = a.x if ymin == None or a.y < ymin: ymin = a.y if ymax == None or a.y > ymax: ymax = a.y dx = xmax-xmin dy = ymax-ymin #print "dx", dy, ymax, ymin range = min( (600.0/dx, 450.0/dy))/2 xp = 640-range*dx yp = 480-range*dy xtrans = lambda xx: range*(xx - xmin)+xp/2 ytrans = lambda xx: range*(xx - ymin)+yp/2 for b in mol.edges: a1, a2 = b.vertices x1 = xtrans( a1.x) x2 = xtrans( a2.x) y1 = ytrans( a1.y) y2 = ytrans( a2.y) paper.create_line( x1, y1, x2, y2, fill='black') paper.create_text( (x1+x2)/2, (y1+y2)/2, text=str( b.order), fill="#F00") for v in mol.vertices: x = xtrans( v.x) y = ytrans( v.y) #paper.create_oval( x-5, y-5, x+5, y+5, fill="#0F0") paper.create_text( x, y, text=v.symbol, fill="#0F0") app.mainloop()
class CoordsCanvas(object): def __init__(self, parent, **kwargs): self._canvas = Canvas(parent, **kwargs) self._canvas.pack(fill=BOTH, expand=YES) self._canvas.bind("<Double-Button-1>", self.on_double_click) self._canvas.bind("<Shift-Button-1>", self.on_shift_button_click) self._canvas.bind("<Control-Button-1>", self.on_ctrl_button_click) self._canvas.bind("<Alt-Button-1>", self.on_alt_button_click) self._canvas.bind("<Option-Button-1>", self.on_alt_button_click) self._canvas.bind("<Double-Button-1>", self.on_double_click) self._canvas.bind("<ButtonPress-1>", self.on_button_press) self._canvas.bind("<ButtonRelease-1>", self.on_button_release) self._event_receiver = None self._dragger = Dragger() def on_double_click(self, _): if hasattr(self._event_receiver, 'zoom_in'): self._event_receiver.zoom_in() def on_shift_button_click(self, _): if hasattr(self._event_receiver, 'zoom_out'): self._event_receiver.zoom_out() def on_ctrl_button_click(self, event): if hasattr(self._event_receiver, 'add'): self._event_receiver.add(event.x, event.y) def on_alt_button_click(self, event): if hasattr(self._event_receiver, 'remove'): self._event_receiver.remove(event.x, event.y) def on_button_press(self, event): self._dragger.start(event.x, event.y) def on_button_release(self, event): if hasattr(self._event_receiver, 'move'): self._dragger.drag_to(event.x, event.y, self._event_receiver.move) def create_circle(self, x, y, r, **kwargs): return self._canvas.create_oval(x - r, y - r, x + r, y + r, **kwargs) def create_text(self, x, y, **kwargs): return self._canvas.create_text(x, y, **kwargs) def get_width(self): return self._canvas.winfo_reqwidth() def get_height(self): return self._canvas.winfo_reqheight() def set_event_receiver(self, receiver): self._event_receiver = receiver def destroy(self, item): self._canvas.delete(item) def destroy_all(self): self._canvas.delete("all")
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)
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)
class ResultsTable(Frame): """A custom table widget which displays words alongside the users guesses""" def __init__(self, parent, width=400, height=200): Frame.__init__(self, parent) self.canvas = Canvas(self, width=width, height=height, bg="#FFFFFF") self.canvas.configure(bd=2, relief=SUNKEN) self.canvas.pack(side=LEFT) self.centre_line = self.canvas.create_line(0, 0, 0, 0) scrollbar = Scrollbar(self) scrollbar.pack(side=RIGHT, fill=Y) scrollbar.configure(command=self.canvas.yview) self.canvas.configure(yscrollcommand=scrollbar.set, scrollregion=(0, 0, width, height)) self.width=width self.height_in_lines = height/18 self.item_count = 0 self.font = ("Helvetica", 12) def add_word(self, word): """Add a word to the table""" top = 20*self.item_count if top > 200: #If necessary extend scroll region downwards self.canvas.configure(scrollregion=(0, 0, self.width, top+20)) colour = "#139E1C" if word.isCorrect else "#F30000" #Draw the word in the left column self.canvas.create_text(2, top, anchor=NW, text=word, font=self.font) #Draw the guess in the right column self.canvas.create_text(self.width/2+2, top, anchor=NW, text=word.answer, font=self.font, fill=colour) #Draw a line to separate this row from those below self.canvas.create_line(0, top+19, self.width, top+19) #Extend centre line of tablr self.canvas.coords(self.centre_line, self.width/2, 0, self.width/2, top+19) self.item_count += 1 def add_list(self, word_list): """Add a list to the table""" for word in word_list: self.add_word(word) def clear(self): """Clear the table of all words""" self.item_count = 0 self.canvas.delete(ALL)
class FrameTk(object): def __init__(self, height, width, box_size, title = "Tk", bg = None): self.BOX_SIZE = box_size self.main = Tk() self.main.wm_title(title) self.canvas = Canvas(self.main, height = height, width = width, bg = bg) self.canvas.pack() def run(self): self.main.mainloop() def repeat(self, end, timeMillis, callback): def _repeat(end, time, func): if self.sma.stop: return if end > 0: end -= 1 self.repeat(end, time, func) func() self._draw() self.canvas.after(timeMillis, _repeat, end, timeMillis, callback) def after(self, timeMillis, callback): def _callback(time, func): if self.sma.stop: return self.after(time, func) func() self._draw() self.canvas.after(timeMillis, _callback, timeMillis, callback) def _draw(self): pass def drawTkImage(self, x, y, tkimage): self.canvas.create_image(x, y, anchor = NW, image = tkimage) def drawText(self, x, y, text, color = 'black', size = 8): self.canvas.create_text(x, y, anchor = NW, text = text, font = ('Arial', size), width = self.BOX_SIZE, fill = color)
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()
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)
class engWindow: def __init__(self, parent): self.value2 = Canvas(parent, bg=black, height=50, width=50) self.text = self.value2.create_text(160, 270, text="Loading", fill=white, font=(textFont, 10)) def update(self): pass def hide(self): pass def show(self): pass
class StartFrame(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.start_canvas = Canvas(self, width=600, height=250, bg="#FFFFFF") self.start_canvas.pack() buttonStart = Button(self, text="Start", width=10, command=self.start) buttonEdit = Button(self, text="Edit Lists", command=self.parent.show_editor) self.list_menu_var = StringVar(self) self.list_menu_var.set("Random List") self.start_canvas.create_window(300, 200, window=buttonStart) self.menu = self.start_canvas.create_window(300, 150) self.start_canvas.create_window(520, 230, window=buttonEdit) self.start_canvas.create_text(300, 100, font=("Helvetica", 25), text="Select a list:") self.update_list() self.update() def start(self): self.parent.start_game(self.selected_list) def update(self, event=None): list_name = self.list_menu_var.get() for word_list in self.parent.list_list: if word_list.name == list_name: self.selected_list = word_list def update_list(self): list_menu = OptionMenu(self, self.list_menu_var, *self.parent.list_list, command=self.update) list_menu.configure(width=30) self.start_canvas.itemconfig(self.menu, window=list_menu) def welcomeMessage(self): self.start_canvas.create_text((10, 10), anchor=NW, text="Welcome, %s." %(self.parent.user.username), font=("Helvetica", 15))
def __init__(self): self.dimx = 0 self.dimy = 0 self.popup_dim = Tk() self.popup_dim.title("Dimensions") center(self.popup_dim, 200, 120) self.popup_dim.resizable(False, False) canvas = Canvas(self.popup_dim, width=200, height=120, bg="#eff") dimx = Entry(self.popup_dim, width=5, relief="raised") dimy = Entry(self.popup_dim, width=5, relief="raised") ok = Button(self.popup_dim, text="OK", command=lambda: self.setrootdimension(dimx.get(), dimy.get()), width=1, font="../font/myfont 6 bold", fg="#eee") canvas.create_window(100, 30, window=dimx) canvas.create_text(65, 30, text="X=") canvas.create_window(100, 60, window=dimy) canvas.create_text(65, 60, text="Y=") canvas.create_window(100, 85, window=ok) canvas.pack()
class Interface(Frame): def __init__(self, master=Tk()): Frame.__init__(self, master) self.grid() self.llbutton = Button(self, text="Linked List", command=self.createLL) self.llbutton.grid() self.canvas = Canvas(master, bg="white", height=750, width=1000) self.canvas.pack() def createLL(): LL.linked_list() print "Linked List chosen" def drawNode(self, coord, rad, val): self.canvas.create_oval((coord[0], coord[1], coord[0], coord[1]), state="normal", width=rad) self.canvas.create_text((coord[0], coord[1]), text=val) def drawArrow(self, src, dest): if src[0] > dest[0]: x1 = src[0] - 20 x2 = dest[0] + 20 elif src[0] < dest[0]: x1 = src[0] + 20 x2 = dest[0] - 20 if src[1] > dest[1]: y1 = src[1] - 20 y2 = dest[1] + 20 elif src[1] < dest[1]: y1 = src[1] + 20 y2 = dest[1] - 20 self.canvas.create_line(x1, y1, x2, y2, arrowshape="8 10 7", arrow="last") dx = dest[0] - src[0] dy = dest[1] - dest[0] m = dy / dx inv = (dx / dy) * -1
def show_word(word): t = time() select = [0] root = Tk() root.title('CrazyEnglish') try: root.call('wm', 'iconphoto', root._w, PhotoImage(file='english.png')) except Exception: print 'Error loading icon' root.geometry( str(root.winfo_screenwidth()) + 'x' + str(root.winfo_screenheight()) + '+0+0') #root.winfo_screenheight() root.resizable(False, False) root.protocol('WM_DELETE_WINDOW', lambda: exit(root, select)) canvas = Canvas(root) #,bg='green') canvas.place(x=100, y=100, width=800, height=50) canvas.create_text(0, 0, text=word[0], anchor='nw', font=('', 14), fill='red') canvas.create_text(0, 30, text='(' + word[1] + ')', anchor='nw') entry = Entry(root, font=('', 10)) entry.place(x=100, y=200, width=800, height=30) Button(root, text='OK', command=lambda: press_btn(root, entry, word[0])).place(x=100, y=250, height=30, width=80) root.after(0, lambda: close_window(root, t)) entry.focus_force() root.mainloop() return select[0]
class GUI(object): def __init__(self, world): self.ticks = 0 self.world = world self.width = world.width self.height = world.height self.root = Tk() self.root.title("Mars Explorer") window_x, window_y = self._compute_window_coords() self.root.geometry('%dx%d+%d+%d' % (self.width, self.height, window_x, window_y)) self.canvas = Canvas(self.root, width=self.width, height=self.height) self.canvas.pack() self.canvas.after(1, self._tick) def start(self): self.root.mainloop() def _tick(self): # Stop if done. if self.world.is_done(): return self.world.tick() self._draw() self.ticks += 1 self.canvas.after(1, self._tick) def _draw(self): self.canvas.delete('all') self.world.draw(self.canvas) for entity in self.world.entities: entity.draw(self.canvas) self.canvas.create_text(self.width - 20, 10, text=str(self.ticks)) self.canvas.create_text(self.width - 70, 30, text='Rocks in carriers: %d' % self.world.rocks_in_carriers()) self.canvas.create_text(self.width - 70, 50, text='Rocks delivered: %d' % self.world.rocks_collected) self.canvas.create_text(self.width - 55, 70, text='Total rocks: %d' % self.world.num_rocks) def _compute_window_coords(self): # http://stackoverflow.com/a/14912644/742501 screen_width = self.root.winfo_screenwidth() screen_height = self.root.winfo_screenheight() window_x = screen_width / 2 - self.width / 2 window_y = screen_height / 2 - self.height / 2 return window_x, window_y
class GetRoot: def __init__(self, root, dimx, dimy): self.root = root self.root.title("Projet Python DIC1") center(self.root, dimx, dimy) self.dimx = dimx self.dimy = dimy self.canvas = Canvas(self.root, width=self.dimx, height=self.dimy, bg="#eee") def root_fermer(self): if askyesno('Confirmer la fermeture', 'Êtes-vous sûr de vouloir quitter?'): self.root.quit() def clear_root(self): for w in self.root.winfo_children(): w.destroy() def presentation(self): self.canvas.create_text(self.dimx / 2, self.dimy / 2, text="Mamour Tall - Cheikh Tidiane Diop") self.canvas.pack() def navigation(self): bouton_effacer = Button(self.root, text="Effacer", relief="raised", font="/font/myfont 8 bold", command=lambda: self.clear_root, bg="#eee", fg="black", activebackground="#dcc") bouton_prec = Button(self.root, text="Precedent", relief="raised", font="/font/myfont 8 bold", command="", bg="#eee", fg="black", activebackground="#dcc") bouton_quitt = Button(self.root, text="Quitter", command=self.root_fermer, relief="raised", font="/font/myfont 8 bold", bg="#eee", fg="black", activebackground="#dcc") bouton_effacer.pack() bouton_prec.pack() bouton_quitt.pack() self.canvas.create_window(self.dimx / 2 + 18, self.dimy - 20, window=bouton_effacer) self.canvas.create_window(60, self.dimy - 20, window=bouton_prec) self.canvas.create_window(self.dimx - 40, self.dimy - 20, window=bouton_quitt)
class Interface(Frame): def __init__(self,master=Tk()): Frame.__init__(self,master) self.grid() self.llbutton = Button(self,text="Linked List", command = self.createLL) self.llbutton.grid() self.canvas = Canvas(master,bg="white",height=750,width=1000) self.canvas.pack() def createLL(): LL.linked_list() print "Linked List chosen" def drawNode(self,coord,rad,val): self.canvas.create_oval((coord[0],coord[1],coord[0],coord[1]),state="normal",width=rad) self.canvas.create_text((coord[0],coord[1]),text=val) def drawArrow(self,src,dest): if src[0] > dest[0]: x1 = src[0] - 20 x2 = dest[0] + 20 elif src[0] < dest[0]: x1 = src[0] + 20 x2 = dest[0] - 20 if src[1] > dest[1]: y1 = src[1] - 20 y2 = dest[1] + 20 elif src[1] < dest[1]: y1 = src[1] + 20 y2 = dest[1] - 20 self.canvas.create_line(x1,y1,x2,y2,arrowshape="8 10 7", arrow="last") dx = dest[0] - src[0] dy = dest[1] - dest[0] m = dy/dx inv = (dx/dy)*-1
class Plotter: def __init__(self): self.colors = ["red", "green"] self.window = Tk() self.window.title("R-L Reinfolge") self.c = Canvas(master=self.window, width = 300, height= 250, bg="white") self.c.create_text(20, 20, text="rechts") self.c.create_text(20, 220, text="links") self.c.pack() t = right - left self.pens = [] for i in range(len,(t)): self.pens.append(Pen (self.c, t[i], self.colors[i%4])) thread.start_new_thread(self.update, ()) self.window.mainloop() def update(self): while True: for i in range(60): for pen in self.pens: pen.draw(i*5) time.sleep(1) self.c.delete("point")
def __init__(self, tweet): Toplevel.__init__(self) self.wm_attributes("-topmost", 1) self.tweet = tweet self.wm_overrideredirect(True) self.lines = [] self.width = 300 self.height = 48 lines = self.splitTextToLines(tweet.text, lastindex = 30, threshold = 8) self.addLinesToHeight(lines) self.geometry("%dx%d+%d+%d" % (self.width, self.height, 200, 200)) canvas = Canvas(self, borderwidth=0, relief="sunken") canvas.pack() self.createLayout(canvas) author = tweet.author canvas.create_text(30, 6, text="@" + author, fill="white", anchor=NW) self.renderText(canvas, lines)
class ResultsTable(Frame): def __init__(self, parent, width=400, height=200): Frame.__init__(self, parent) self.canvas = Canvas(self, width=width, height=height, bg="#FFFFFF") self.canvas.configure(bd=2, relief=SUNKEN) self.canvas.pack(side=LEFT) self.centre_line = self.canvas.create_line(0, 0, 0, 0) scrollbar = Scrollbar(self) scrollbar.pack(side=RIGHT, fill=Y) scrollbar.configure(command=self.canvas.yview) self.canvas.configure(yscrollcommand=scrollbar.set, scrollregion=(0, 0, width, height)) self.width=width self.height_in_lines = height/18 self.item_count = 0 self.font = ("Helvetica", 12) def add_word(self, word): top = 20*self.item_count if top > 200: self.canvas.configure(scrollregion=(0, 0, self.width, top+20)) colour = "#139E1C" if word.isCorrect else "#F30000" self.canvas.create_text(2, top, anchor=NW, text=word, font=self.font) self.canvas.create_text(self.width/2+2, top, anchor=NW, text=word.answer, font=self.font, fill=colour) self.canvas.create_line(0, top+19, self.width, top+19) self.canvas.coords(self.centre_line, self.width/2, 0, self.width/2, top+19) self.item_count += 1 def add_list(self, word_list): for word in word_list: self.add_word(word) def clear(self): self.item_count = 0 self.canvas.delete(ALL)
class bootWindow: def __init__(self, parent): logging.info("Host IP: " + get_ip()) self.screen = Canvas(parent, bg=black, height=480, width=320) self.screen.place(x=0, y=0) Testline = self.screen.create_line(160, 0, 160, 480, fill=red) Testline2 = self.screen.create_line(0, 240, 320, 240, fill=red) self.img = ImageTk.PhotoImage(Image.open("images/logo.PNG")) self.imglabel = Label(self.screen, image=self.img).place(x=160, y=150, anchor="center") self.text = self.screen.create_text(160, 270, text="Loading, Please wait...", fill=white, font=(textFont, 13)) self.p = ttk.Progressbar(self.screen, orient="horizontal", length=200, mode='determinate') self.p.place(x=160, y=300, anchor="center") # LOAD ALL THE STUFF!! parent.update() self.p.step(10) parent.update() #time.sleep(1) self.p.step(10) parent.update() #time.sleep(1) self.p.step(30) parent.update() time.sleep(1) self.screen.destroy() self.p.destroy() def hide(self): pass def show(self): pass def update(self): pass def __del__(self): pass
class Viewport(Frame): def __init__(self, parent=None, canvassize=500): Frame.__init__(self, parent) # Incredibly, it's a pain to extract the canvas width,height directly # from the canvas widget itself, so we store these here and push them # down to the actual canvas widget whenever they change. self.canvaswidth = canvassize self.canvasheight = canvassize # The flag for whether we display the camera or not is in menu.py # as part the of menubar class. self.readoutid = 0 self.framewidth = -1 # Will be set elsewhere self.frameheight = -1 self.pack(side=BOTTOM, anchor=S, expand=YES, fill=BOTH) self.canvas = Canvas(self, width=canvassize, \ height=canvassize, bg='white') self.canvas.pack() ########################### # DRAW_READOUT class function: # - Build the text strings for the camera readout display # - If a readout is already on the screen, remove it # - Draw the new readout # This routine does NOT check the menu.py variable that determines # whether or not we should actually draw the readout. It's the # caller's responsibility to do that. # def draw_readout(self, camera): text1 = 'Camera:' text2 = "x=%d y=%d z=%d" % (round(camera.t[0]), \ round(camera.t[1]), round(camera.t[2])) text3 = "Rotation = %d" % (round(degrees(camera.yrot))) text4 = "%s\n%s\n%s" % (text1, text2, text3) if self.readoutid: self.canvas.delete(self.readoutid) self.readoutid = self.canvas.create_text(5,5, text=text4, \ anchor=NW) def undraw_readout(self): if self.readoutid: self.canvas.delete(self.readoutid) self.readoutid = 0
class Viewport(Frame): def __init__(self, parent=None, canvassize=500): Frame.__init__(self, parent) # Incredibly, it's a pain to extract the canvas width,height directly # from the canvas widget itself, so we store these here and push them # down to the actual canvas widget whenever they change. self.canvaswidth = canvassize self.canvasheight = canvassize # The flag for whether we display the camera or not is in menu.py # as part the of menubar class. self.readoutid = 0 self.framewidth = -1 # Will be set elsewhere self.frameheight = -1 self.pack(side=BOTTOM, anchor=S, expand=YES, fill=BOTH) self.canvas = Canvas(self, width=canvassize, \ height=canvassize, bg='white') self.canvas.pack() ########################### # DRAW_READOUT class function: # - Build the text strings for the camera readout display # - If a readout is already on the screen, remove it # - Draw the new readout # This routine does NOT check the menu.py variable that determines # whether or not we should actually draw the readout. It's the # caller's responsibility to do that. # def draw_readout(self, camera): text1 = 'Camera:' text2 = "x=%d y=%d z=%d" % (round(camera.t[0]), \ round(camera.t[1]), round(camera.t[2])) text3 = "Rotation = %d" % (round(degrees(camera.yrot))) text4 = "%s\n%s\n%s" % (text1, text2, text3) if self.readoutid: self.canvas.delete(self.readoutid) self.readoutid = self.canvas.create_text(5,5, text=text4, \ anchor=NW) def undraw_readout(self): if self.readoutid: self.canvas.delete(self.readoutid) self.readoutid = 0
class engWindow: def __init__(self, parent): self.value2 = Canvas(parent, bg=black, height=50, width=50) self.text = self.value2.create_text(160, 270, text="Loading", fill=white, font=(textFont, 10)) def update(self): pass def hide(self): pass def show(self): pass
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)
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)
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)
class Application(Frame): def __init__(self, parent, game): Frame.__init__(self, parent, background="green") self.parent = parent self.game = game self.initUI() self.canvas = Canvas(self) self.draw() def initUI(self): self.parent.title("Football") self.pack(fill=BOTH, expand=1) def draw(self): self.game.next_round() LAYOUT = self.game.get_layout() self.canvas.delete("all") self.canvas.create_text(300, 20, anchor=W, font="Purisa", text="RESULT " + str(LAYOUT[7][0]) + ":" + str(LAYOUT[7][1])) self.canvas.create_text(50, 20, anchor=W, font="Purisa", text="Control WSAD" ) self.canvas.create_text(650, 20, anchor=W, font="Purisa", text="Control ARROWS" ) x0 = 10 y0 = 40 # WHOLE FIELD self.canvas.create_rectangle(x0, y0, x0 + LAYOUT[0], y0 + LAYOUT[1], outline="white", fill="green", width=2) self.canvas.create_rectangle(x0, y0, x0 + LAYOUT[0]/2, y0 + LAYOUT[1], outline="white", fill="green", width=1) self.canvas.create_oval(x0 + LAYOUT[0]/2 -1 , y0 + LAYOUT[1]/2 - 1, x0 + LAYOUT[0]/2, y0 + LAYOUT[1]/2, outline="white", fill="white", width=4) # GOALKEEPER FIELDS self.canvas.create_rectangle(x0, y0 + LAYOUT[1]/2 - LAYOUT[3][1]/2, x0 + LAYOUT[3][0], y0 + LAYOUT[1]/2 + LAYOUT[3][1]/2, outline="white", fill="green", width=2) self.canvas.create_rectangle(x0 + LAYOUT[0] - LAYOUT[3][0], y0 + LAYOUT[1]/2 - LAYOUT[3][1]/2, x0 + LAYOUT[0], y0 + LAYOUT[1]/2 + LAYOUT[3][1]/2, outline="white", fill="green", width=2) # GOALPOSTS self.canvas.create_rectangle(x0 - 5, y0 + LAYOUT[1]/2 - LAYOUT[2]/2, x0, y0 + LAYOUT[1]/2 + LAYOUT[2]/2, fill="black") self.canvas.create_rectangle(x0 + LAYOUT[0]-1, y0 + LAYOUT[1]/2 - LAYOUT[2]/2, x0 + LAYOUT[0] + 5, y0 + LAYOUT[1]/2 + LAYOUT[2]/2, fill="black") # PLAYERS self.canvas.create_oval(x0 + LAYOUT[4][0]-LAYOUT[8][0][0], y0 + LAYOUT[4][1]-LAYOUT[8][0][0], x0 + LAYOUT[4][0] + LAYOUT[8][0][0], y0 + LAYOUT[4][1] + LAYOUT[8][0][0], fill="blue") self.canvas.create_oval(x0 + LAYOUT[5][0]-LAYOUT[8][1][0], y0 + LAYOUT[5][1]-LAYOUT[8][1][0], x0 + LAYOUT[5][0] + LAYOUT[8][1][0], y0 + LAYOUT[5][1] + LAYOUT[8][1][0], fill="gray") # BALL self.canvas.create_oval(x0 + LAYOUT[6][0]-LAYOUT[8][2][0], y0 + LAYOUT[6][1]-LAYOUT[8][2][0], x0 + LAYOUT[6][0] + LAYOUT[8][2][0], y0 + LAYOUT[6][1] + LAYOUT[8][2][0], fill="white") self.canvas.pack(fill=BOTH, expand=1) self.after(1, self.draw)
class LoginFrame(Frame): """Class which controls the Login and Register screens of the spelling aid""" def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.db = self.parent.db #Create login screen widgets font = ("Helvetica", 20) self.userEntry = Entry(self.parent, width=15, font=font) self.passEntry = Entry(self.parent, width=15, show='*', font=font) self.passEntry.bind('<Return>', self.login) buttonSubmit = Button(self.parent, text="Login", command=self.login, width=10) buttonRegSwitch = Button(self.parent, text="New User", command=self.viewRegister, width=10) #Create register screen widgets self.userRegEntry = Entry(self.parent, width=15, font=font) self.passRegEntry = Entry(self.parent, width=15, show='*', font=font) self.passRegEntry.bind('<Return>', self.register) buttonRegister = Button(self.parent, text="Register", command=self.register, width=10) buttonBack = Button(self.parent, text="Back", command=self.viewLogin, width=10) #Create a canvas for each screen and populate self.login_canvas = Canvas(self, width=600, height=250, bg="#FFFFFF") self.register_canvas = Canvas(self, width=600, height=250, bg="#FFFFFF") self.login_canvas.create_text(300, 40, text="Login", font=font, fill="#004183") self.login_canvas.create_text(170, 80, text="Username:"******"Password:"******"Register", font=font, fill="#004183") self.register_canvas.create_text(170, 80, text="Username:"******"Password:"******"Check the user's input and allow access if it is correct""" usernameGiven = self.userEntry.get() passwordGiven = self.passEntry.get() userDetails = self.db.sql("""SELECT * FROM users WHERE username='******'""" %(usernameGiven.lower().strip())) #Check that the username exists if len(userDetails)==1: passHash = userDetails[0][2] #Check that the password is correct if (hashlib.sha1(passwordGiven).hexdigest() == passHash): #Details are correct, unlock application self.parent.login(User(userDetails[0])) loginFailed = False else: loginFailed = True else: loginFailed = True if loginFailed: #If details are incorrect show an error message tkMessageBox.showerror("Login Failed", "Invalid username or password") self.userEntry.delete(0, END) self.passEntry.delete(0, END) def register(self): """Register a new user with provided input""" username = self.userRegEntry.get() passwd = self.passRegEntry.get() if username != '' and passwd != '': username = username.lower().strip() passHash = hashlib.sha1(passwd).hexdigest() self.db.sql("""INSERT INTO users (username, passwd) VALUES ('%s', '%s')"""%(username, passHash)) self.viewLogin() def viewRegister(self): """Switch to the register screen""" self.login_canvas.pack_forget() self.register_canvas.pack() def viewLogin(self): """Switch to the login screen""" self.register_canvas.pack_forget() self.login_canvas.pack()
class SudokuUI(Frame): """ Sudoku grid UI class. Adapted from: http://newcoder.io/gui/part-4/ """ def __init__(self, parent, board): self.game = board Frame.__init__(self, parent) self.parent = parent self.row, self.col = -1, -1 self.new_entry = None self.previous_guess = None self.game_state = 0 self.scores = [] self.__initUI() def __initUI(self): """ Initialize sudoku playing field grid and bind clicking and entry handlers.""" self.parent.title("Sudoku") self.pack(fill=BOTH, expand=1) self.canvas = Canvas(self, width=WIDTH, height=HEIGHT) self.canvas.grid(row=1, column=0) self.__draw_grid() self.__draw_puzzle() self.__draw_scores() self.canvas.bind("<Button-1>", self.__cell_clicked) self.canvas.bind("<Key>", self.__key_pressed) def __draw_grid(self): """ Draw Sudoku 3x3 x 3x3 grid.""" for i in xrange(10): color = "blue" if i % 3 == 0 else "gray" x0 = MARGIN + i * SIDE y0 = MARGIN x1 = MARGIN + i * SIDE y1 = HEIGHT - MARGIN self.canvas.create_line(x0, y0, x1, y1, fill=color) x0 = MARGIN y0 = MARGIN + i * SIDE x1 = WIDTH - MARGIN y1 = MARGIN + i * SIDE self.canvas.create_line(x0, y0, x1, y1, fill=color) def __draw_puzzle(self): """ Draw Sudoku solution numbers.""" self.canvas.delete("numbers") for i in xrange(9): for j in xrange(9): answer = self.game.board[i][j] if answer != 0: x = MARGIN + j * SIDE + SIDE / 2 y = MARGIN + i * SIDE + SIDE / 2 self.canvas.create_text(x, y, text=answer, tags="numbers") def __cell_clicked(self, event): """ Handle a single cell click and highlight the clicked cell. :param event: """ x, y = event.x, event.y if MARGIN < x < WIDTH - MARGIN and MARGIN < y < HEIGHT - MARGIN: self.canvas.focus_set() # get row and col numbers from x,y coordinates row, col = (y - MARGIN) / SIDE, (x - MARGIN) / SIDE # if cell was selected already - deselect it if (row, col) == (self.row, self.col): self.row, self.col = -1, -1 elif self.game.board[row][col] == 0: self.row, self.col = row, col self.__draw_cursor() def __draw_cursor(self): """ Draw the red outline for the selected square.""" self.canvas.delete("cursor") if self.row >= 0 and self.col >= 0: x0 = MARGIN + self.col * SIDE + 1 y0 = MARGIN + self.row * SIDE + 1 x1 = MARGIN + (self.col + 1) * SIDE - 1 y1 = MARGIN + (self.row + 1) * SIDE - 1 self.canvas.create_rectangle(x0, y0, x1, y1, outline="green", tags="cursor") def __key_pressed(self, event): """ Handle solution number entry.""" if self.row >= 0 and self.col >= 0 and event.char in "123456789" and self.game_state == 1: self.new_entry = (self.row, self.col, int(event.char)) self.col, self.row = -1, -1 self.__draw_puzzle() self.__draw_cursor() def __draw_scores(self): self.score_list = Treeview(self, columns=('name', 'score')) self.score_list['show'] = 'headings' self.score_list.heading('name', text='Name') self.score_list.column('name', width=80, anchor=CENTER) self.score_list.heading('score', text='Score') self.score_list.column('score', width=80, anchor=CENTER) self.score_list.grid(row=1, column=1, padx=(0, 20)) def __update_scores(self, scores): self.score_list.delete(*self.score_list.get_children()) for entry in scores: self.score_list.insert('', 'end', values=(entry[0], entry[1])) def show_winner(self, score, user_id): if score[2] == user_id: winner_text = "YOU HAVE WON!" else: winner_text = "Player " + str(score[0]) + " has won!" tkMessageBox.showwarning("A WINNER IS FOUND", winner_text) def update_board(self, root, board, scores, new_game_state): """ Update board during the gameplay. If all players are not connected, solution entry is not permitted. In case of a wrong answer the selected square is flashed red for a fraction of a second to notify the player about his life decisions. :param root: :param board: :param new_game_state: :return entered value: """ return_val = None self.__update_scores(scores) # Check for game state, if it is "0", just return, else continue the game if self.game_state == 0: root.update() if new_game_state != 0: self.game_state = new_game_state return return_val # If previous guess was not correct flash it red if self.previous_guess is not None and board[self.previous_guess[0]][self.previous_guess[1]] != \ self.previous_guess[2]: row, col, _ = self.previous_guess x0 = MARGIN + col * SIDE + 1 y0 = MARGIN + row * SIDE + 1 x1 = MARGIN + (col + 1) * SIDE - 1 y1 = MARGIN + (row + 1) * SIDE - 1 self.canvas.create_rectangle(x0, y0, x1, y1, fill="red", tags="fail") else: self.canvas.delete("fail") # Initiate return value to none, update the board and draw it self.game.update_board(board) self.__draw_puzzle() root.update() # If user has entered anything in between, write it into the return value and previous guess and return if self.new_entry is not None: return_val = self.new_entry self.previous_guess = self.new_entry self.new_entry = None else: self.previous_guess = None return return_val
vy += 1 space_count += 1 root = Tk() canvas = Canvas(root, width=w, height=h, bg='black') canvas.pack() #creates background img1 = Image.open('earthrise.jpg').resize((w, h)) pmg1 = ImageTk.PhotoImage(img1) canvas.create_image(w / 2, h / 2, image=pmg1) #opens eagle.jpg img2 = Image.open('eagle.jpg').resize((200, 200)) pmg2 = ImageTk.PhotoImage(img2) ship = canvas.create_image(w / 4, 0, image=pmg2) #creates landing pad 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') f = ('Times', 36, 'bold') txt = canvas.create_text(w - 100, 50, text='0.0', font=f, fill='white') #creates text fuel_bar = canvas.create_text(w - 100, 80, font=f, fill='white') canvas.after(1000, tick) root.mainloop() f_obj.close()
class WorldWar(Frame): canvas = None menu = None selected = None selected_2 = None state = SELECT player = PLAYER_ALLY def __init__(self, parent): # IMAGES ######### self.NODE_IMG = [ ImageTk.PhotoImage(Image.open("img/node1.png")), ImageTk.PhotoImage(Image.open("img/node2.png")), ImageTk.PhotoImage(Image.open("img/node3.png")), ImageTk.PhotoImage(Image.open("img/node4.png")), ] self.BG = ImageTk.PhotoImage(Image.open("img/map.png")) self.FLAG_AXIS = ImageTk.PhotoImage(Image.open("img/flag_axis.png")) self.FLAG_ALLY = ImageTk.PhotoImage(Image.open("img/flag_ally.png")) self.CANNON = ImageTk.PhotoImage(Image.open("img/cannon.png")) self.FORTRESS = ImageTk.PhotoImage(Image.open("img/fort.png")) ################# Frame.__init__(self, parent) self.parent = parent self.init_ui() self.update_ui() self.update_menu() def init_ui(self): self.parent.title("World War II") self.pack(fill=tk.BOTH, expand=1) self.canvas = Canvas(self, width=WINDOW_W - 200, height=WINDOW_H) # self.canvas.bind("<Motion>",self.motion) self.canvas.bind("<Button-1>", self.click) self.canvas.pack(side=tk.LEFT) def update_ui(self): self.canvas.create_image(0, 0, anchor=tk.NW, image=self.BG) for n in Logic.network: self.canvas.create_image(n.x, n.y, anchor=tk.CENTER, image=self.NODE_IMG[n.rank]) if n.occupant == PLAYER_AXIS: self.canvas.create_image(n.x, n.y - NODE_R[n.rank] - 5, anchor=tk.S, image=self.FLAG_AXIS) if n.occupant == PLAYER_ALLY: self.canvas.create_image(n.x, n.y - NODE_R[n.rank] - 5, anchor=tk.S, image=self.FLAG_ALLY) if n.cannon or n.cannon_time > -1: self.canvas.create_image(n.x - NODE_R[n.rank] - 5, n.y, anchor=tk.E, image=self.CANNON) if n.cannon_time > -1: self.canvas.create_text( n.x - NODE_R[n.rank] - 5, n.y + NODE_R[n.rank] + 5, anchor=tk.NE, text=str(Logic.cannon_makers) ) if n.fortress or n.fortress_time > -1: self.canvas.create_image(n.x + NODE_R[n.rank] + 5, n.y, anchor=tk.W, image=self.FORTRESS) if n.fortress_time > -1: self.canvas.create_text( n.x + NODE_R[n.rank] + 5, n.y + NODE_R[n.rank] + 5, anchor=tk.NW, text=str(Logic.fortress_makers) ) self.canvas.create_text(n.x, n.y + NODE_R[n.rank] + 5, anchor=tk.N, text=str(n.allowed)) if self.selected is not None: self.canvas.create_oval( self.selected.x - NODE_R[self.selected.rank] - 5, self.selected.y - NODE_R[self.selected.rank] - 5, self.selected.x + NODE_R[self.selected.rank] + 5, self.selected.y + NODE_R[self.selected.rank] + 5, width=3, outline="#0000FF", ) for n in Logic.adjacent_levels(self.selected): self.canvas.create_line(self.selected.x, self.selected.y, n.x, n.y, arrow=tk.LAST, dash=(3, 3)) if self.selected_2 is not None: self.canvas.create_oval( self.selected_2.x - NODE_R[self.selected_2.rank] - 5, self.selected_2.y - NODE_R[self.selected_2.rank] - 5, self.selected_2.x + NODE_R[self.selected_2.rank] + 5, self.selected_2.y + NODE_R[self.selected_2.rank] + 5, width=3, outline="#FF0000", ) def update_menu(self): if self.menu is not None: self.menu.destroy() self.menu = Frame(self, width=200, height=WINDOW_H) self.menu.pack(fill=tk.X) plr = Label(self.menu, text=("Player: ALLIES" if self.player is PLAYER_ALLY else "Player: AXIS")) plr.pack(fill=tk.X, padx=5, pady=5) if self.selected_2 is not None: if self.selected_2.cannon_time > -1: txt = "%d moves to build" % (Logic.cannon_ready - self.selected_2.cannon_time) if self.selected_2.cannon: txt = "cannon present" lbl_can = Label(self.menu, text=txt, image=self.CANNON, compound=tk.LEFT) lbl_can.pack(fill=tk.X, padx=5, pady=5) if self.selected_2.fortress_time > -1: txt = "%d moves to build" % (Logic.fortress_ready - self.selected_2.fortress_time) if self.selected_2.fortress: txt = "fortress present" lbl_can = Label(self.menu, text=txt, image=self.FORTRESS, compound=tk.LEFT) lbl_can.pack(fill=tk.X, padx=5, pady=5) move = Button(self.menu, text="CONFIRM MOVE", command=self.confirm_move) move.pack(fill=tk.X, padx=5, pady=5) PHOTO = ImageTk.PhotoImage(Image.open(self.selected_2.image)) data = Label( self.menu, text=self.selected_2.text, wraplength=200, padx=5, pady=5, image=PHOTO, compound=tk.BOTTOM ) data.pack(fill=tk.X, padx=5, pady=5) return if self.state == MOVE: an = Label(self.menu, text="Select another node") an.pack(fill=tk.X, padx=5, pady=5) return if self.selected is not None: if self.selected.cannon_time > -1: txt = "%d moves to build" % (Logic.cannon_ready - self.selected.cannon_time) if self.selected.cannon: txt = "cannon present" lbl_can = Label(self.menu, text=txt, image=self.CANNON, compound=tk.LEFT) lbl_can.pack(fill=tk.X, padx=5, pady=5) if self.selected.fortress_time > -1: txt = "%d moves to build" % (Logic.fortress_ready - self.selected.fortress_time) if self.selected.fortress: txt = "fortress present" lbl_can = Label(self.menu, text=txt, image=self.FORTRESS, compound=tk.LEFT) lbl_can.pack(fill=tk.X, padx=5, pady=5) if self.player == self.selected.occupant: move = Button(self.menu, text="MOVE", command=self.move) move.pack(fill=tk.X, padx=5, pady=5) if not self.selected.cannon: mk_can = Button(self.menu, text="MAKE CANNON", command=self.mk_cannon) mk_can.pack(fill=tk.X, padx=5, pady=5) if not self.selected.fortress: mk_ft = Button(self.menu, text="MAKE FORTRESS", command=self.mk_fortress) mk_ft.pack(fill=tk.X, padx=5, pady=5) PHOTO = ImageTk.PhotoImage(Image.open(self.selected.image)) data = Label( self.menu, text=self.selected.text, wraplength=200, padx=5, pady=5, image=PHOTO, compound=tk.BOTTOM ) data.pack(fill=tk.X, padx=5, pady=5) def confirm_move(self): num = askinteger("Troops:", "Enter number of troops :", parent=self) if num == 0: showerror("Error", "Kuch to hila") else: result = None if self.selected.cannon: if askyesno("Move cannon?", parent=self): result = Logic.move(self.selected, self.selected_2, num, True, 0, 0) else: result = Logic.move(self.selected, self.selected_2, num, False, 0, 0) else: result = Logic.move(self.selected, self.selected_2, num, False, 0, 0) if result[0]: self.next_move() else: showerror("Error", result[1]) self.selected_2 = None self.state = SELECT self.update_ui() self.update_menu() def move(self): self.state = MOVE self.update_ui() self.update_menu() def mk_cannon(self): result = Logic.move(self.selected, None, 0, False, 1, 0) if result[0]: self.next_move() else: showerror("Error", result[1]) def mk_fortress(self): result = Logic.move(self.selected, None, 0, False, 0, 1) if result[0]: self.next_move() else: showerror("Error", result[1]) def click(self, event): if self.state == SELECT: self.selected = get_node_at(event.x, event.y) else: self.selected_2 = get_node_at(event.x, event.y) if self.selected_2 == self.selected: self.selected_2 = None self.update_ui() self.update_menu() def next_move(self): if Logic.network[0].occupant == PLAYER_AXIS: showinfo("Game Ends", "Player AXIS wins!") sys.exit() if Logic.network[17].occupant == PLAYER_ALLY: showinfo("Game Ends", "Player ALLY wins!") sys.exit() self.selected = None self.selected_2 = None self.state = SELECT self.player = PLAYER_AXIS if self.player is PLAYER_ALLY else PLAYER_ALLY self.update_ui() self.update_menu()
class World(Tk): # def __init__(self,filename=None,block=50,debug=True,delay=0.25,image=False,width=10,height=10): def __init__(self, filename=None, block=50, debug=True, delay=0.25, image=True, width=10, height=10): Tk.__init__(self) self.title("") arg, self.width, self.height = block, width, height self.photos = [ PhotoImage(file=(k + ".gif")) for k in ["east", "north", "west", "south"] ] self.beepers, self.ovals, self.numbers, self.robots, self.walls = {},{},{},{},{} self.m, self.n, self.t, self.delay = arg * (width + 3), arg * ( height + 3), arg, delay self.debug, self.useImage = debug, image a, b, c = self.t + self.t / 2, self.m - self.t - self.t / 2, self.n - self.t - self.t / 2 self.canvas = Canvas(self, bg="white", width=self.m, height=self.n) self.canvas.pack() count = 1 for k in range(2 * self.t, max(self.m, self.n) - self.t, self.t): if k < b: self.canvas.create_line(k, c, k, a, fill="red") self.canvas.create_text(k, c + self.t / 2, text=str(count), font=("Times", max(-self.t * 2 / 3, -15), "")) if k < c: self.canvas.create_line(b, k, a, k, fill="red") self.canvas.create_text(a - self.t / 2, self.n - k, text=str(count), font=("Times", max(-self.t * 2 / 3, -15), "")) count += 1 self.canvas.create_line(a, c, b, c, fill="black", width=3) self.canvas.create_line(a, a, a, c, fill="black", width=3) if filename is not None: self.readWorld(filename) self.refresh() def readWorld(self, filename): try: infile = open("worlds\\%s.wld" % filename, "r") except IOError: try: infile = open("worlds/%s.wld" % filename, "r") except IOError: infile = open(filename, "r") text = infile.read().split("\n") infile.close() for t in text: if t.startswith("eastwestwalls"): s = t.split(" ") y, x = int(s[1]), int(s[2]) self.addWall(x, y, -1, y) if t.startswith("northsouthwalls"): s = t.split(" ") x, y = int(s[1]), int(s[2]) self.addWall(x, y, x, -1) if t.startswith("beepers"): s = t.split(" ") y, x, n = int(s[1]), int(s[2]), int(s[3]) if n is infinity: self.addInfiniteBeepers(x, y) else: for k in range(n): self.addBeeper(x, y) def pause(self): sleep(self.delay) def isBeeper(self, x, y): return (x, y) in self.beepers.keys() and not self.beepers[(x, y)] == 0 def countRobots(self, x, y): if (x, y) not in self.robots.keys(): return 0 return len(self.robots[(x, y)]) def crash(self, x1, y1, x2, y2): if 0 in (x1, y1, x2, y2): return True if (x2, y2) in self.walls.keys() and (x1, y1) in self.walls[(x2, y2)]: return True if (x1, y1) in self.walls.keys() and (x2, y2) in self.walls[(x1, y1)]: return True return False def addInfiniteBeepers(self, x, y): flag = (x, y) not in self.beepers.keys() or self.beepers[(x, y)] is 0 self.beepers[(x, y)] = infinity text = "oo" a, b = self.t + x * self.t, self.n - (self.t + y * self.t) t = self.t / 3 if flag: self.ovals[(x, y)] = self.canvas.create_oval(a - t, b - t, a + t, b + t, fill="black") self.numbers[(x, y)] = self.canvas.create_text( a, b, text=text, fill="white", font=("Times", max(-self.t / 2, -20), "")) else: self.canvas.itemconfig(self.numbers[(x, y)], text=text) if (x, y) in self.robots.keys(): for robot in self.robots[(x, y)]: robot.lift() def addBeeper(self, x, y): if (x, y) in self.beepers.keys() and self.beepers[(x, y)] is infinity: return flag = (x, y) not in self.beepers.keys() or self.beepers[(x, y)] is 0 if flag: self.beepers[(x, y)] = 1 else: self.beepers[(x, y)] += 1 text = str(self.beepers[(x, y)]) a, b = self.t + x * self.t, self.n - (self.t + y * self.t) t = self.t / 3 if flag: self.ovals[(x, y)] = self.canvas.create_oval(a - t, b - t, a + t, b + t, fill="black") self.numbers[(x, y)] = self.canvas.create_text( a, b, text=text, fill="white", font=("Times", max(-self.t / 2, -20), "")) else: self.canvas.itemconfig(self.numbers[(x, y)], text=text) if (x, y) in self.robots.keys(): for robot in self.robots[(x, y)]: robot.lift() def removeBeeper(self, x, y): if self.beepers[(x, y)] is infinity: return self.beepers[(x, y)] -= 1 flag = self.beepers[(x, y)] is 0 text = str(self.beepers[(x, y)]) if flag: self.canvas.delete(self.ovals[(x, y)]) self.canvas.delete(self.numbers[(x, y)]) else: self.canvas.itemconfig(self.numbers[(x, y)], text=text) if (x, y) in self.robots.keys(): for robot in self.robots[(x, y)]: robot.lift() def addWall(self, x1, y1, x2, y2): if not x1 == x2 and not y1 == y2: return if x1 == x2: y1, y2 = min(y1, y2), max(y1, y2) if y1 == -1: y1 = y2 for k in range(y1, y2 + 1): self.walls.setdefault((x1, k), []).append((x1 + 1, k)) a, b = self.t + x1 * self.t + self.t / 2, self.n - ( self.t + k * self.t) + self.t / 2 c, d = self.t + x1 * self.t + self.t / 2, self.n - ( self.t + k * self.t) - self.t / 2 self.canvas.create_line(a, b + 1, c, d - 1, fill="black", width=3) else: x1, x2 = min(x1, x2), max(x1, x2) if x1 == -1: x1 = x2 for k in range(x1, x2 + 1): self.walls.setdefault((k, y1), []).append((k, y1 + 1)) a, b = self.t + k * self.t - self.t / 2, self.n - ( self.t + y1 * self.t) - self.t / 2 c, d = self.t + k * self.t + self.t / 2, self.n - ( self.t + y1 * self.t) - self.t / 2 self.canvas.create_line(a - 1, b, c + 1, d, fill="black", width=3) def draw(self, x, y, d, img): if self.useImage: if img is not None: self.canvas.delete(img) x, y = self.t + x * self.t, self.n - (self.t + y * self.t) photo = self.photos[d / 90] img = self.canvas.create_image(x, y, image=photo) return img else: t, angle = self.t / 2, 120 x, y = self.t + x * self.t, self.n - (self.t + y * self.t) x1, y1 = x + 3**0.5 * t / 2 * cos( radians(d)), y - 3**0.5 * t / 2 * sin(radians(d)) x2, y2 = x + t * cos(radians(d + angle)), y - t * sin( radians(d + angle)) x3, y3 = x + t / 4 * cos(radians(d + 180)), y - t / 4 * sin( radians(d + 180)) x4, y4 = x + t * cos(radians(d - angle)), y - t * sin( radians(d - angle)) if img is not None: self.canvas.delete(img) img = self.canvas.create_polygon(x1, y1, x2, y2, x3, y3, x4, y4, fill="blue") return img def erase(self, img): self.canvas.delete(img) def recordMove(self, count, x1, y1, x2, y2): for robot in self.robots[(x1, y1)]: if robot.count == count: self.robots[(x1, y1)].remove(robot) self.robots.setdefault((x2, y2), []).append(robot) break def lift(self, img): self.canvas.lift(img) def refresh(self): self.canvas.update() self.pause() def register(self, x, y, robot): self.robots.setdefault((x, y), []).append(robot) def remove(self, x, y, robot): self.robots[(x, y)].remove(robot)
class PlayerApp(Frame): def __init__(self, root, player): Frame.__init__(self, root) self.root = root self.config(bd=0, bg='black', highlightbackground='black') self.pack() self._canvas = Canvas(root, width=(WIN_WIDTH), height=WIN_HEIGHT, bd=0, bg='black', highlightbackground='black') self._canvas.pack() self.player = player self._img_mode = 4 self._img_mode_count = 6 # Scale the size to with the entire width of our window. # TODO(igorc): Avoid scaling? Or auto-rescale when window resizes. frame1_size = self.player.get_frame_size() img1_aspect = frame1_size[0] / 2 / frame1_size[1] img1_width = int(WIN_WIDTH * 0.95) self._img1_size = (img1_width, int(img1_width / img1_aspect)) if self.player.is_fin_enabled() or self.player.is_kinect_enabled(): text_y = 0.07 img1_y = 0.28 img2_y = 0.56 else: text_y = 0.04 img1_y = 0.23 img2_y = 0.54 # Undo gamma correction in LED preview, otherwise it is too dark. # Keep a fixed value to have better feedback on LED gamma changes. left_x = int(WIN_WIDTH * 0.025) self._img1 = ImageTk.PhotoImage('RGBA', self._img1_size, gamma=2.2) self._img2 = ImageTk.PhotoImage('RGBA', self._img1_size) self._canvas.create_image(left_x, int(WIN_HEIGHT * img1_y), anchor='nw', image=self._img1) self._canvas.create_image(left_x, int(WIN_HEIGHT * img2_y), anchor='nw', image=self._img2) if self.player.is_fin_enabled(): img3_width = int(WIN_WIDTH * 0.15) # The fin dimensions are 150x240 inches. self._img3_size = (img3_width, int(img3_width * 1.1)) self._img3 = ImageTk.PhotoImage('RGBA', self._img3_size, gamma=2.2) left_scale = 0.60 if self.player.is_kinect_enabled() else 0.65 self._canvas.create_image(int(WIN_WIDTH * left_scale), int(WIN_HEIGHT * 0.05), anchor='nw', image=self._img3) if self.player.is_kinect_enabled(): img4_width = int(WIN_WIDTH * 0.15) self._img4_size = (img4_width, int(img4_width * 0.7)) self._img4 = ImageTk.PhotoImage('RGB', self._img4_size, gamma=2.2) self._canvas.create_image(int(WIN_WIDTH * 0.8), int(WIN_HEIGHT * 0.08), anchor='nw', image=self._img4) self._main_label = self._canvas.create_text( (left_x, WIN_HEIGHT * text_y), fill='#fff', anchor='nw', justify='left', font=("Sans Serif", 16)) self._canvas.itemconfig(self._main_label, text="this is the text") self.root.bind('q', lambda e: player.volume_up()) self.root.bind('a', lambda e: player.volume_down()) self.root.bind('m', lambda e: self.switch_mask()) self.root.bind('g', lambda e: player.gamma_up()) self.root.bind('b', lambda e: player.gamma_down()) self.root.bind('h', lambda e: player.visualization_volume_up()) self.root.bind('n', lambda e: player.visualization_volume_down()) self.root.bind('v', lambda e: player.toggle_visualization()) self.root.bind('t', lambda e: self.toggle_visualizer_render()) self.root.bind('d', lambda e: player.toggle_hdr_mode()) self.root.bind('o', lambda e: player.select_next_preset(False)) self.root.bind('p', lambda e: player.select_next_preset(True)) self.root.bind('l', lambda e: player.lock_screen()) self.root.bind('0', lambda e: player.stop_effect()) self.root.bind('1', lambda e: player.play_effect('slowblink')) self.root.bind('2', lambda e: player.play_effect('radiaterainbow')) self.root.bind('3', lambda e: player.play_effect('threesine')) self.root.bind('4', lambda e: player.play_effect('plasma')) self.root.bind('5', lambda e: player.play_effect('rider')) self.root.bind('6', lambda e: player.play_effect('flame')) self.root.bind('7', lambda e: player.play_effect('glitter')) self.root.bind('8', lambda e: player.play_effect('slantbars')) self.root.bind('9', lambda e: player.play_effect('textticker')) self.root.bind('!', lambda e: player.play_effect('solidcolor')) self.root.bind('@', lambda e: player.play_effect('randompixels')) self.root.bind('#', lambda e: player.play_effect('teststripes')) self.root.bind('$', lambda e: player.play_effect('blink')) self.root.bind('%', lambda e: player.play_effect('chameleon')) self.root.bind('^', lambda e: player.play_effect('indicator')) self.root.bind('&', lambda e: player.play_effect('flick')) self.root.bind('*', lambda e: player.play_effect('textstay')) self.root.bind('<space>', lambda e: player.toggle()) self.root.bind('<Up>', lambda e: player.prev()) self.root.bind('<Down>', lambda e: player.next()) self.root.bind('<Left>', lambda e: player.skip_backward()) self.root.bind('<Right>', lambda e: player.skip_forward()) self.root.protocol('WM_DELETE_WINDOW', lambda: self.quit()) self.root.after(1000 / FPS / 4, lambda: self.update()) self.running = True def run_effect(self, effect): self.player.effect = effect def switch_mask(self): self._img_mode += 1 self._img_mode = self._img_mode % self._img_mode_count def toggle_visualizer_render(self): if (self._img_mode % 3) == 0: self._img_mode += 1 elif (self._img_mode % 3) == 2: self._img_mode += 2 else: self._img_mode += 2 self._img_mode = self._img_mode % self._img_mode_count def quit(self): self.running = False def _paste_images(self, images, mode): # Always use LED image as the first image. frame1 = images[2].copy() if images[2] else None frame3 = images[3].copy() if images[3] else None frame4 = images[4].copy() if images[4] else None crop_rect = None frame_size = self.player.get_frame_size() if mode < 3: crop_rect = (0, 0, frame_size[0] / 2, frame_size[1]) else: crop_rect = (frame_size[0] / 2, 0, frame_size[0], frame_size[1]) if frame1: frame1 = frame1.crop(crop_rect) if (mode % 3) == 0: # Second is intermediate image by default. frame2 = images[1].copy() if images[1] else None if frame2: frame2 = frame2.crop(crop_rect) elif (mode % 3) == 1: # Otherwise show original image. frame2 = images[0].copy() if images[0] else None if frame2 and mode >= 3: frame2 = frame2.transpose(Image.FLIP_LEFT_RIGHT) else: # Show black if disabled. frame2 = Image.new('RGBA', self._img1_size, (0, 0, 0, 0)) if frame1: self._img1.paste(frame1.resize(self._img1_size)) if frame2: self._img2.paste(frame2.resize(self._img1_size)) if frame3: # Dorsal fin self._img3.paste(frame3.resize(self._img3_size)) if frame4: # Kinect self._img4.paste(frame4.resize(self._img4_size)) def update(self): try: mode = self._img_mode if (mode % 3) == 1 and self.player.is_playing_effect(): mode -= 1 need_original = (mode % 3) == 1 need_intermediate = (mode % 3) == 0 images = self.player.get_frame_images(need_original, need_intermediate) if images: self._paste_images(images, mode) status_lines = self.player.get_status_lines() self._canvas.itemconfig(self._main_label, text='\n'.join(status_lines)) # TODO(igorc): Reschedule after errors. self.root.after(1000 / FPS / 4, lambda: self.update()) except KeyboardInterrupt: self.quit()
class SudokuUI(Frame): def __init__(self, parent, game): self.game = game self.parent = parent Frame.__init__(self, parent) self.row, self.col = 0, 0 self.__initUI() def __initUI(self): self.parent.title("Sudoku") self.pack(fill=BOTH, expand=1) self.canvas = Canvas(self, width=WIDTH, height=HEIGHT) self.canvas.pack(fill=BOTH, side=TOP) clear_button = Button(self, text="Clear answers", command=self.__clear_answers) clear_button.pack(fill=BOTH, side=BOTTOM) self.__draw_grid() self.__draw_puzzle() self.canvas.bind("<Button-1>", self.__cell_clicked) self.canvas.bind("<Key>", self.__key_pressed) def __draw_grid(self): for i in xrange(10): color = "blue" if i % 3 == 0 else "gray" x0 = MARGIN + i * SIDE y0 = MARGIN x1 = MARGIN + i * SIDE y1 = HEIGHT - MARGIN self.canvas.create_line(x0, y0, x1, y1, fill=color) x0 = MARGIN y0 = MARGIN + i * SIDE x1 = WIDTH - MARGIN y1 = MARGIN + i * SIDE self.canvas.create_line(x0, y0, x1, y1, fill=color) def __draw_puzzle(self): self.canvas.delete("numbers") for i in xrange(9): for j in xrange(9): answer = self.game.puzzle[i][j] if answer != 0: x = MARGIN + j * SIDE + SIDE / 2 y = MARGIN + i * SIDE + SIDE / 2 original = self.game.start_puzzle[i][j] color = "black" if answer == original else "sea green" self.canvas.create_text(x, y, text=answer, tags="numbers", fill=color) def __clear_answers(self): self.game.start() self.canvas.delete("victory") self.__draw_puzzle() def __cell_clicked(self, event): if self.game.game_over: return x, y = event.x, event.y if (MARGIN < x < WIDTH - MARGIN and MARGIN < y < HEIGHT - MARGIN): self.canvas.focus_set() row, col = (y - MARGIN) / SIDE, (x - MARGIN) / SIDE if (row, col) == (self.row, self.col): self.row, self.col = -1, -1 elif self.game.puzzle[row][col] == 0 or self.game.puzzle[row][ col] != self.game.start_puzzle[row][col]: self.row, self.col = row, col else: self.row, self.col = -1, -1 self.__draw_cursor() def __draw_cursor(self): self.canvas.delete("cursor") if self.row >= 0 and self.col >= 0: x0 = MARGIN + self.col * SIDE + 1 y0 = MARGIN + self.row * SIDE + 1 x1 = MARGIN + (self.col + 1) * SIDE - 1 y1 = MARGIN + (self.row + 1) * SIDE - 1 self.canvas.create_rectangle(x0, y0, x1, y1, outline="red", tags="cursor") def __key_pressed(self, event): if self.game.game_over: return if self.row >= 0 and self.col >= 0 and event.char in "1234567890": self.game.puzzle[self.row][self.col] = int(event.char) self.col, self.row = -1, -1 self.__draw_puzzle() self.__draw_cursor() if self.game.check_win(): self.__draw_victory() def __draw_victory(self): x0 = y0 = MARGIN + SIDE * 2 x1 = y1 = MARGIN + SIDE * 7 self.canvas.create_oval(x0, y0, x1, y1, tags="victory", fill="dark orange", outline="orange") x = y = MARGIN + 4 * SIDE + SIDE / 2 self.canvas.create_text(x, y, text="You win!", tags="winner", fill="white", font=("Arial", 32))
class TopLevelView(BaseView): TEXT_LABEL_OFFSET = 35 ROD_BOX_START_X = 50 ROD_BOX_START_Y = 45 ROD_BOX_WIDTH = 70 ROD_BOX_HEIGHT = 25 ROD_BOX_VERTICAL_OFFSET = 10 # other values are the same like for the ROD boxes ROS_BOX_START_X = 150 ROS_BOX_START_Y = 45 def __init__(self, tkRoot, systems, app, logger): BaseView.__init__(self, tkRoot, app, logger) self.systems = systems # names of all subsystems # Canvas options width, height seem not necessary ... self.canvas = Canvas(self.tkRoot, bg=BaseView.CANVAS_BG_COLOR) self.canvas.pack(expand=YES, fill=BOTH) self.__createRodBoxes() self.__createRosBoxes() self.__createRodRosLines() self.name = "TOP" # name of this special view self.app.addActiveView(self.name, self) # special top view # add logo logo = PhotoImage(file="doc/logo.gif") self.canvas.create_image(conf.GUI_WIDTH - 20, conf.GUI_HEIGHT - 20, image=logo) self.canvas.image = logo # keep a reference, otherwise it won't appear def __openRosDetailedView(self, comp): try: rosTree = self.app.rosTrees[comp.name] # every view (except for TopLevelView) has a tree node # acting as root for such particular view treeRootNode = rosTree.root v = View(self.tkRoot, self.app, comp, treeRootNode, self.logger) v.createContent() self.logger.debug("View created for '%s'" % comp) except KeyError: m = "ROS data n/a for '%s'" % comp self.logger.warn(m) tkMessageBox.showwarning("Quit", m, parent=self.tkRoot) def openDetailedView(self, comp): if comp.group == "ROS": # check if view which is to be open has not been opened already if self.app.isViewActive(comp.name): m = ("View '%s' is already among active windows, " "not created." % comp.name) self.logger.warn(m) tkMessageBox.showwarning("Quit", m, parent=self.tkRoot) else: self.__openRosDetailedView(comp) else: m = "No view available for '%s' " % comp self.logger.warn(m) tkMessageBox.showwarning("Quit", m, parent=self.tkRoot) def __createRodBoxes(self): state = NotAssociated() group = "ROD" # title self.canvas.create_text( TopLevelView.ROD_BOX_START_X + TopLevelView.TEXT_LABEL_OFFSET, TopLevelView.ROD_BOX_START_Y - TopLevelView.ROD_BOX_HEIGHT, text=group, font=self.bigFont) for i in range(len(self.systems)): x0 = TopLevelView.ROD_BOX_START_X y0 = (TopLevelView.ROD_BOX_START_Y + (i * (TopLevelView.ROD_BOX_HEIGHT + TopLevelView.ROD_BOX_VERTICAL_OFFSET))) x1 = x0 + TopLevelView.ROD_BOX_WIDTH y1 = y0 + TopLevelView.ROD_BOX_HEIGHT box = Box(group, self.systems[i], self.canvas) box.create(x0, y0, x1, y1, state.color) box.text(x0 + TopLevelView.TEXT_LABEL_OFFSET, y0 + TopLevelView.ROD_BOX_HEIGHT / 2, self.systems[i], self.boxTitleFont) self.compStore.append(box) def __createRosBoxes(self): state = Inactive() group = "ROS" # title self.canvas.create_text( TopLevelView.ROS_BOX_START_X + TopLevelView.TEXT_LABEL_OFFSET, TopLevelView.ROS_BOX_START_Y - TopLevelView.ROD_BOX_HEIGHT, text=group, font=self.bigFont) for i in range(len(self.systems)): # need to get a tree node controlling the created component try: rosTree = self.app.rosTrees[self.systems[i]] node = rosTree.root box = RenderableBox(group, self.canvas, node) except KeyError: # some defined system don't have data (node) to be controlled by box = Box(group, self.systems[i], self.canvas) x0 = TopLevelView.ROS_BOX_START_X y0 = (TopLevelView.ROS_BOX_START_Y + (i * (TopLevelView.ROD_BOX_HEIGHT + TopLevelView.ROD_BOX_VERTICAL_OFFSET))) x1 = x0 + TopLevelView.ROD_BOX_WIDTH y1 = y0 + TopLevelView.ROD_BOX_HEIGHT idBox = box.create(x0, y0, x1, y1, state.color) idText = box.text(x0 + TopLevelView.TEXT_LABEL_OFFSET, y0 + TopLevelView.ROD_BOX_HEIGHT / 2, self.systems[i], self.boxTitleFont) dch = DoubleClickHandler(box, self) # bind both IDs - box and text in the box self.canvas.tag_bind(idBox, "<Double-1>", dch) self.canvas.tag_bind(idText, "<Double-1>", dch) self.compStore.append(box) def __createRodRosLines(self): group = "RODROSLINE" for i in range(len(self.systems)): x0 = TopLevelView.ROD_BOX_START_X + TopLevelView.ROD_BOX_WIDTH y0 = (TopLevelView.ROS_BOX_START_Y + (i * (TopLevelView.ROD_BOX_HEIGHT + TopLevelView.ROD_BOX_VERTICAL_OFFSET)) + TopLevelView.ROD_BOX_HEIGHT / 2) x1 = TopLevelView.ROS_BOX_START_X y1 = y0 line = Line(group, self.systems[i], self.canvas) line.create(x0, y0, x1, y1) self.compStore.append(line)
class ReversiView: ''' Creates window with the reversi board and controls the game using gui. ''' def __init__(self, players, boardSize=8, w=850, h=410): ''' :param w: width of the window :param h: height of the window ''' self.root = Tk() self.boardSize = boardSize self.stone_board = [-1] * self.boardSize for row in range(self.boardSize): self.stone_board[row] = [-1] * self.boardSize self.w = w self.h = h self.offx = 5 self.offy = 5 self.gridw = 410 self.gridh = 410 self.gridspacing = 50 self.ovalDiamPart = 0.8 self.colors = ["blue", "red"] self.root.title("Reversi") self.interactive_player_ids = [] self.interactivePlayers = [] self.interractivePlayerName = 'Interactive' self.possiblePlayers = { self.interractivePlayerName: -1, } for player_name in players.keys(): self.possiblePlayers[player_name] = players[player_name] self.wrong_move = False ws = self.root.winfo_screenwidth() hs = self.root.winfo_screenheight() x = (ws / 2) - (self.w / 2) y = (hs / 2) - (self.h / 2) self.root.geometry('%dx%d+%d+%d' % (self.w, self.h, x, y)) self.draw_game_grid() self.draw_game_info_grid() self.game_state = GameState.STOPPED def set_game(self, game): ''' Sets the game to the GUI. ''' self.game = game def set_board(self, board): ''' Sets the game board to the GUI. ''' self.board = board def draw_stone(self, x, y, color): ''' Draw stone on position [x,y] in gui :param x: x coordinate of the stone :param y: y coordinate of the stone :param color: 0 for blue, 1 fro red ''' x_coord = (self.gridspacing * x) + (1.0 - self.ovalDiamPart) * self.gridspacing y_coord = (self.gridspacing * y) + (1.0 - self.ovalDiamPart) * self.gridspacing diameter = self.ovalDiamPart * self.gridspacing self.clear_stone(x, y) self.stone_board[x][y] = self.grid.create_oval(x_coord, y_coord, x_coord + diameter, y_coord + diameter, fill=self.colors[color]) def clear_stone(self, x, y): ''' Delete stone on position [x,y] from the gui :param x: x coordinate of the stone :param y: y coordinate of the stone ''' if self.stone_board[x][y] != -1: self.grid.delete(self.stone_board[x][y]) self.stone_board[x][y] = -1 def draw_game_info_grid(self): ''' Draw control and inform part of game to right side of the window. ''' self.info = Canvas(self.root, height=self.h - self.gridh, width=self.w - self.gridw) self.info.pack(side="left") label_stones = Label(self.info, text="Current stones:", font=("Helvetica", 10)) label_stones.grid(row=1, column=0) label_max_time = Label(self.info, text="Max time:", font=("Helvetica", 10)) label_max_time.grid(row=2, column=0) label_scale = Label(self.info, text='Game speed [ms]:', font=("Helvetica", 10), foreground='black') label_scale.grid(row=5, column=0) helv36 = font.Font(family="helvetica", size=16, weight='bold') self.scale_var = IntVar() scale = Scale(self.info, variable=self.scale_var, command=self.sleep_time_change_handler, from_=0, to=1000, resolution=10, width="15", orient=HORIZONTAL, length="225") scale.set(200) scale.grid(row=5, column=1, columnspan=3) self.button = Button(self.info, text="Play", width="20", height="2", command=self.play_button_click_handler) self.button['font'] = helv36 self.button.grid(row=6, column=0, columnspan=4) # labels for num stones, max time of move, etc self.label_player_stones = [-1, -1] self.label_player_max_time = [-1, -1] self.labels_inform = [-1, -1] self.labels_player_name = [-1, -1] self.option_menus = [-1, -1] self.option_menus_vars = [-1, -1] for i in range(2): self.label_player_stones[i] = Label(self.info, text='2', font=("Helvetica", 10), foreground=self.colors[i]) self.label_player_stones[i].grid(row=1, column=2 * (i + 1) - 1, columnspan=2) self.label_player_max_time[i] = Label(self.info, text="%.2f [ms]" % 0.0, font=("Helvetica", 10), foreground=self.colors[i]) self.label_player_max_time[i].grid(row=2, column=2 * (i + 1) - 1, columnspan=2) self.labels_inform[i] = Label(self.info, text='', font=("Helvetica", 10), foreground='black') self.labels_inform[i].grid(row=i + 3, column=0, columnspan=4) self.labels_player_name[i] = Label(self.info, text="Player%d:" % (i), font=("Helvetica", 12), foreground=self.colors[i]) self.labels_player_name[i].grid(row=0, column=2 * i) self.option_menus_vars[i] = StringVar(self.root) self.option_menus_vars[i].set(self.interractivePlayerName) self.option_menus[i] = OptionMenu(self.info, self.option_menus_vars[i], *self.possiblePlayers) self.option_menus[i].grid(row=0, column=2 * i + 1) def draw_game_grid(self): ''' Draw empty 8x8 grid on the left side of the window. ''' self.grid = Canvas(self.root, bg="white", height=self.gridh, width=self.gridw) self.grid.bind("<Button 1>", self.place_stone_click_handler) gridsize = self.boardSize offy = self.offy offx = self.offx w = self.gridw h = self.gridh spacing = self.gridspacing # line around self.grid.create_line(offx, offy, offx, h - offy, w - offx, h - offy, w - offx, offy, offx, offx) for x in range(0, gridsize): for y in range(0, gridsize): arrayText = '[' + str(y) + ',' + str(x) + ']' self.grid.create_text(offx + (spacing * x) + spacing / 2, offy + (spacing * y) + spacing / 2, text=arrayText) # line rows for rowy in range(offy + spacing, h - offy, spacing): self.grid.create_line(offx, rowy, w - offx, rowy) # line columns for colx in range(offx + spacing, w - offx, spacing): self.grid.create_line(colx, offy, colx, h - offy) self.grid.pack(side="left") def sleep_time_change_handler(self, event): ''' Called after scale value change, updates the wait time between moves. :param event: slider change event ''' self.game.sleep_time_ms = self.scale_var.get() def play_button_click_handler(self): ''' Button listener for Play/Pause/RePlay etc. On button click prints slider value and start game. ''' # set the players from dropdown menu if game is stopped if self.game_state == GameState.STOPPED: print("game_state " + str(self.game_state)) self.interactive_player_ids = [] for i in range(2): print(self.option_menus_vars[i].get()) if self.option_menus_vars[i].get( ) == self.interractivePlayerName: self.interactive_player_ids.append(i) if i == 0: self.game.player1.name = self.interractivePlayerName else: self.game.player2.name = self.interractivePlayerName else: if i == 0: player_class = self.possiblePlayers[ self.option_menus_vars[i].get()] self.game.player1 = player_class( self.game.player1_color, self.game.player2_color) else: player_class = self.possiblePlayers[ self.option_menus_vars[i].get()] self.game.player2 = player_class( self.game.player2_color, self.game.player1_color) self.game.clear_game() self.game.current_player = self.game.player1 self.game.current_player_color = self.game.player1_color print('player1 ' + str(self.game.player1_color)) print('player2 ' + str(self.game.player2_color)) #play game or start game if interactive if len(self.interactive_player_ids) != 0: if self.game_state == GameState.STOPPED: print("revert this commented out section below") #if not self.board.can_play(self.game.current_player, self.game.current_player_color): # self.game.clear_game() # self.button['text'] = 'Play' #else: self.game_state = GameState.RUNNING self.button['text'] = 'RePlay' print('can play ', self.interactive_player_ids) inform_str = 'Player%d plays' % ( self.interactive_player_ids[0]) self.inform(inform_str, 'green') if len(self.interactive_player_ids ) == 1 and self.interactive_player_ids[0] == 1: self.game.play_game(self.interactive_player_ids[0]) else: self.game_state = GameState.STOPPED self.button['text'] = 'Play' self.game.clear_game() # self.game.play_game(self.interactivePlayerId) else: if self.game_state == GameState.STOPPED or self.game_state == GameState.PAUSED: print('start') print('player1 ' + str(self.game.player1_color)) print('player2 ' + str(self.game.player2_color)) self.button['text'] = 'Pause' self.game.sleepTimeMS = self.scale_var.get() if self.game_state == GameState.STOPPED: self.game.clear_game() self.game.pause(False) self.game_state = GameState.RUNNING print('player1 ' + str(self.game.player1_color)) print('player2 ' + str(self.game.player2_color)) self.game.play_game() print('game exited') if self.board.can_play(self.game.current_player_color ) and not self.wrong_move: print('set pause state') self.button['text'] = 'Continue' self.game_state = GameState.PAUSED else: print('set stopped state') self.button['text'] = 'RePlay' self.game_state = GameState.STOPPED # self.game.clear_game() elif self.game_state == GameState.RUNNING: print('pause') self.game_state = GameState.PAUSED self.game.pause(True) def print_score(self): ''' Set number of stones for both players. ''' stones = self.board.get_score() self.print_player_num_stones(0, stones[0]) self.print_player_num_stones(1, stones[1]) def print_num_stones(self, stones): ''' Set number of stones for both players. :param stones: array of player number of stones ''' self.print_player_num_stones(0, stones[0]) self.print_player_num_stones(1, stones[1]) def print_player_num_stones(self, playerID, stones): ''' Set player number of stones. :param playerID: 0 for player 1, 1 for player 2 :param maxTime: maximal time of player ''' self.label_player_stones[playerID]['text'] = str(stones) self.root.update() def print_move_max_times(self, maxTimesMS): ''' Print maximal times for both players to the gui. :param max_times_ms: array of max time needed for move. ''' self.print_player_move_max_time(0, maxTimesMS[0]) self.print_player_move_max_time(1, maxTimesMS[1]) def print_player_move_max_time(self, playerID, maxTime): ''' Set player maximal time. :param playerID: 0 for player 1, 1 for player 2 :param maxTime: maximal time of player ''' self.label_player_max_time[playerID]['text'] = '%.2f [ms]' % maxTime self.root.update() def print_board_state(self): ''' Show the state of the board in gui. ''' # self.board.print_board() for y in range(self.board.board_size): for x in range(self.board.board_size): if self.board.board[y][x] == -1: self.clear_stone(x, y) else: self.draw_stone(x, y, self.board.board[y][x]) self.root.update() def place_stone_click_handler(self, event): ''' For interactive player places stone to mouse click position. :param event: mouse click event ''' print("place_stone_click_handler") if self.game_state != GameState.STOPPED and len( self.interactive_player_ids ) >= 1 and self.game.current_player_color in self.interactive_player_ids: pos_move = [ int((event.y - self.offy) / self.gridspacing), int((event.x - self.offx) / self.gridspacing) ] if self.board.is_correct_move(pos_move, self.game.current_player_color): next_player_id = self.game.play_move(pos_move) self.print_board_state() self.print_score() self.print_move_max_times(self.game.max_times_ms) inform_str = 'Player%d plays' % ( self.game.current_player_color) self.inform(inform_str, 'green') if len(self.interactive_player_ids) == 1: self.game.play_game(self.interactive_player_ids[0]) if next_player_id == -1: self.game_state = GameState.STOPPED self.button['text'] = 'RePlay' self.game.print_final_info() else: print('incorrect move', pos_move) self.inform( 'incorrect move to %d %d' % (pos_move[0], pos_move[1]), 'red') def inform(self, text_strs, color_str): ''' Show inform text in gui. :param text_strs: string or string array of size 2 that is shown in gui :param color_str: color of shown text_strs ''' inform_str_all = ['', ''] if not isinstance(text_strs, list): inform_str_all[0] = text_strs else: inform_str_all = text_strs # print(inform_str_all) for i in range(2): self.labels_inform[i]['text'] = inform_str_all[i] self.labels_inform[i]['foreground'] = color_str self.root.update()
class SudokuUI(Frame): """ The Tkinter UI, responsible for drawing the board and accepting user input. """ def __init__(self, parent, game): self.game = game Frame.__init__(self, parent) self.parent = parent self.row, self.col = -1, -1 self.__initUI() def __initUI(self): self.parent.title("Sudoku") self.pack(fill=BOTH) self.canvas = Canvas(self, width=WIDTH, height=HEIGHT) self.canvas.pack(fill=BOTH, side=TOP) clear_button = Button(self, text="Clear answers", command=self.__clear_answers) clear_button.pack(fill=BOTH, side=BOTTOM) self.__draw_grid() self.__draw_puzzle() self.canvas.bind("<Button-1>", self.__cell_clicked) self.canvas.bind("<Key>", self.__key_pressed) def __draw_grid(self): """ Draws grid divided with blue lines into 3x3 squares """ for i in range(10): color = "blue" if i % 3 == 0 else "grey" x0 = MARGIN + i * SIDE y0 = MARGIN x1 = MARGIN + i * SIDE y1 = HEIGHT - MARGIN self.canvas.create_line(x0, y0, x1, y1, fill=color) x0 = MARGIN y0 = MARGIN + i * SIDE x1 = WIDTH - MARGIN y1 = MARGIN + i * SIDE self.canvas.create_line(x0, y0, x1, y1, fill=color) def __draw_puzzle(self): self.canvas.delete("numbers") for i in range(9): for j in range(9): answer = self.game.puzzle[i][j] if answer != 0: x = MARGIN + j * SIDE + SIDE / 2 y = MARGIN + i * SIDE + SIDE / 2 original = self.game.start_puzzle[i][j] color = "black" if answer == original else "sea green" self.canvas.create_text(x, y, text=answer, tags="numbers", fill=color) def __draw_cursor(self): self.canvas.delete("cursor") if self.row >= 0 and self.col >= 0: x0 = MARGIN + self.col * SIDE + 1 y0 = MARGIN + self.row * SIDE + 1 x1 = MARGIN + (self.col + 1) * SIDE - 1 y1 = MARGIN + (self.row + 1) * SIDE - 1 self.canvas.create_rectangle(x0, y0, x1, y1, outline="red", tags="cursor") def __draw_victory(self): # create a oval (which will be a circle) x0 = y0 = MARGIN + SIDE * 2 x1 = y1 = MARGIN + SIDE * 7 self.canvas.create_oval(x0, y0, x1, y1, tags="victory", fill="dark orange", outline="orange") # create text x = y = MARGIN + 4 * SIDE + SIDE / 2 self.canvas.create_text(x, y, text="You win!", tags="victory", fill="white", font=("Arial", 32)) def __draw_loose(self): # create a oval (which will be a circle) x0 = y0 = MARGIN + SIDE * 2 x1 = y1 = MARGIN + SIDE * 7 self.canvas.create_oval(x0, y0, x1, y1, tags="victory", fill="yellow", outline="yellow") # create text x = y = MARGIN + 4 * SIDE + SIDE / 2 self.canvas.create_text(x, y, text="You loose!", tags="victory", fill="white", font=("Arial", 32)) def __cell_clicked(self, event): if self.game.game_over: return x, y = event.x, event.y if (MARGIN < x < WIDTH - MARGIN and MARGIN < y < HEIGHT - MARGIN): self.canvas.focus_set() # get row and col numbers from x,y coordinates row, col = (y - MARGIN) // SIDE, (x - MARGIN) // SIDE # if cell was selected already - deselect it if (row, col) == (self.row, self.col): self.row, self.col = -1, -1 elif self.game.check[row][col] == 0: self.row, self.col = row, col else: self.row, self.col = -1, -1 self.__draw_cursor() def __key_pressed(self, event): if self.game.game_over: return if self.row >= 0 and self.col >= 0 and event.char in "1234567890": self.game.puzzle[self.row][self.col] = int(event.char) self.col, self.row = -1, -1 self.__draw_puzzle() self.__draw_cursor() a = self.game.check_win() # print(a) if a == 0: self.__draw_loose() return 0 elif a == 1: self.__draw_victory() def __clear_answers(self): self.game.start() self.canvas.delete("victory") self.__draw_puzzle()
class DiscreteTAMPViewer(object): def __init__(self, rows, cols, width=500, height=250, side=25, block_buffer=10, title='Grid', background='tan', draw_fingers=False): assert (rows <= MAX_ROWS) assert (cols <= MAX_COLS) 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.rows = rows self.cols = cols self.canvas = Canvas(top, width=self.width, height=self.height, background=background) self.canvas.pack() self.side = side self.block_buffer = block_buffer self.draw_fingers = draw_fingers self.cells = {} self.robot = [] self.draw_environment() def transform_r(self, r): return self.table_y1 + r * (self.side + 2 * self.block_buffer ) + 2 * self.block_buffer + self.side / 2 def transform_c(self, c): # assert r >= 0 and r < self.width return self.table_x1 + c * (self.side + 2 * self.block_buffer ) + 2 * self.block_buffer + self.side / 2 def draw_environment(self, table_color='lightgrey', bin_color='grey'): table_width = self.cols * ( self.side + 2 * self.block_buffer) + 2 * self.block_buffer table_height = self.rows * ( self.side + 2 * self.block_buffer) + 2 * self.block_buffer border_buffer = 50 #self.table_x1 = border_buffer self.table_y1 = self.height - table_height - border_buffer self.table_x1 = self.width / 2 - table_width / 2 #self.table_y1 = self.height/2-table_height/2 bin_width = 20 self.environment = [ self.canvas.create_rectangle(self.table_x1, self.table_y1, self.table_x1 + table_width, self.table_y1 + table_height, fill=table_color, outline='black', width=2), self.canvas.create_rectangle(self.table_x1 - bin_width, self.table_y1, self.table_x1, self.table_y1 + table_height, fill=bin_color, outline='black', width=2), self.canvas.create_rectangle(self.table_x1 + table_width, self.table_y1, self.table_x1 + table_width + bin_width, self.table_y1 + table_height, fill=bin_color, outline='black', width=2), self.canvas.create_rectangle(self.table_x1, self.table_y1 + table_height, self.table_x1 + table_width, self.table_y1 + table_height + bin_width, fill=bin_color, outline='black', width=2), self.canvas.create_rectangle( self.table_x1 - bin_width, self.table_y1 + table_height, self.table_x1 + table_width + bin_width, self.table_y1 + table_height + bin_width, fill=bin_color, outline='black', width=2), ] pose_radius = 2 for r in range(self.rows): for c in range(self.cols): x = self.transform_c(c) y = self.transform_r(r) self.environment.append( self.canvas.create_oval(x - pose_radius, y - pose_radius, x + pose_radius, y + pose_radius, fill='black')) def draw_robot(self, r, c, color='yellow'): # TODO - could also visualize as top grasps instead of side grasps grasp_buffer = 3 # 0 | 3 | 5 finger_length = self.side + grasp_buffer # + self.block_buffer finger_width = 10 gripper_length = 20 if self.draw_fingers: gripper_width = self.side + 2 * self.block_buffer + finger_width else: gripper_width = self.side stem_length = 50 stem_width = 20 x = self.transform_c(c) y = self.transform_r( r) - self.side / 2 - gripper_length / 2 - grasp_buffer finger_x = gripper_width / 2 - finger_width / 2 self.robot = [ self.canvas.create_rectangle(x - stem_width / 2., y - stem_length, x + stem_width / 2., y, fill=color, outline='black', width=2), self.canvas.create_rectangle(x - gripper_width / 2., y - gripper_length / 2., x + gripper_width / 2., y + gripper_length / 2., fill=color, outline='black', width=2), ] if self.draw_fingers: self.robot += [ self.canvas.create_rectangle(x + finger_x - finger_width / 2., y, x + finger_x + finger_width / 2., y + finger_length, fill=color, outline='black', width=2), self.canvas.create_rectangle(x - finger_x - finger_width / 2., y, x - finger_x + finger_width / 2., y + finger_length, fill=color, outline='black', width=2), ] self.canvas.update() def draw_block(self, r, c, name='', color='red'): x = self.transform_c(c) y = self.transform_r(r) self.cells[(x, y)] = [ self.canvas.create_rectangle(x - self.side / 2., y - self.side / 2., x + self.side / 2., y + self.side / 2., fill=color, outline='black', width=2), self.canvas.create_text(x, y, text=name), ] # def delete(self, (x, y)): # if (x, y) in self.cells: # self.canvas.delete(self.cells[(x, y)]) def clear(self): self.canvas.delete('all') def save(self, filename): self.canvas.postscript(file='%s.ps' % filename, colormode='color') from PIL import ImageGrab ImageGrab.grab((0, 0, self.width, self.height)).save(filename + '.jpg')
class at_graph(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.u = utils('atoutput.pkl') self.km = dict() self.price = dict() self.km[0] = (min(self.u.all_km), max(self.u.all_km)) self.price[0] = (min(self.u.all_price), max(self.u.all_price)) self.zoom_level = 0 try: self.parent.title("Auto trader results") self.is_standalone = True except: self.is_standalone = False self.style = Style() self.style.theme_use("classic") # Assume the parent is the root widget; make the frame take up the # entire widget size. print self.is_standalone if self.is_standalone: self.w, self.h = map(int, self.parent.geometry().split('+')[0].split('x')) self.w, self.h = 800, 800 else: self.w, self.h = 600, 600 self.c = None # Are they hovering over a data point? self.is_hovering = False # Filter the description strings: lower and whiten any non-matching # data point. self.filter = '' self.re = list() self.replot() def replot(self, zlfrac=None): """Replot the graph. If zlfrac is not None, then it should be a fractional value between 0 and 1; this is used to do smooth zooming, which doesn't plot the axes (it only redraws the car points).""" if self.c is not None: self.c.destroy() self.c = Canvas(self, height=self.h, width=self.w, bd=1, bg='#f3f5f9') self.c.grid(sticky=S, pady=1, padx=1) zl = self.zoom_level if zlfrac is not None: z1l, z1h = self.zoom_price_start z2l, z2h = self.zoom_price_end price_low = z1l + (z2l - z1l) * zlfrac price_high = z1h + (z2h - z1h) * zlfrac z1l, z1h = self.zoom_km_start z2l, z2h = self.zoom_km_end km_low = z1l + (z2l - z1l) * zlfrac km_high = z1h + (z2h - z1h) * zlfrac self.axis((price_low, price_high), 'y', draw=False) self.axis((km_low, km_high), 'x', draw=False) self.car_points(draw=False) else: self.axis(self.price[zl], 'y') self.axis(self.km[zl], 'x') self.car_points() self.pack(fill=BOTH, expand=1) def xyp(self, x, y): "Given x in km and y in $, return canvas position (xp, yp)." xp = int(math.floor((1.0 * x - self.x1) / (self.x2 - self.x1) \ * (self.xp2 - self.xp1) + self.xp1 + 0.5)) yp = int(math.floor((1.0 * y - self.y1) / (self.y2 - self.y1) \ * (self.yp2 - self.yp1) + self.yp1 + 0.5)) return (xp, yp) def axis(self, arange, ax, draw=True): "Add an axis ax='x' or 'y', with arange=(min, max) values." if draw: a1, a2, ast = self.u.axis(*arange) else: a1, a2 = arange ast = (a2 - a1) * 0.2 nt = int(math.floor((a2 - a1) / ast + 0.5)) + 1 st_offset = 50 # Remember the min and max axis values, along with the canvas points # that correspond to each location (xp1 and xp2). This allows us to # calculate where on the canvas a particular (x, y) value falls. if ax == 'x': self.x1, self.x2 = a1, a2 self.xp1, self.xp2 = st_offset, self.w - st_offset self.xtick = [a1 + i * ast for i in range(nt)] # Remember where the midpoint of the axis is, relative to canvas. self.xmid = (self.xp1 + self.xp2) / 2 else: self.y1, self.y2 = a1, a2 self.yp1, self.yp2 = self.h - st_offset, st_offset self.ytick = [a1 + i * ast for i in range(nt)] # Remember where the midpoint of the axis is, relative to canvas. self.ymid = (self.yp1 + self.yp2) / 2 # Figure out tick labels. atick = ['%g' % ((a1 + i * ast) / 1000) for i in range(nt)] # Figure out maximum decimal places on all tick labels, and ensure # they all have that many decimal places. max_dec = max(map(lambda x: 0 if '.' not in x else len(x.split('.')[1]), atick)) if max_dec > 0: atick = map(lambda x: x + '.' + '0'*max_dec if '.' not in x else x + '0'*(max_dec - len(x.split('.')[1])), atick) yst, xst = self.h - st_offset, st_offset # Draw axis line proper, and axis label. if draw: if ax == 'x': self.c.create_line(xst, yst, self.w - st_offset, yst) xp = (xst + self.w - st_offset) / 2 self.c.create_text(xp, yst + 30, text='Mileage (km x 1000)') else: self.c.create_line(xst, yst, xst, st_offset) self.c.create_text(xst, st_offset - 30, text='Price') self.c.create_text(xst, st_offset - 15, text='($000)') tick_anchor = [N, E][ax == 'y'] tick_x, tick_y = xst, yst tick_step = ([self.w, self.h][ax == 'y'] - st_offset * 2 * 1.0) / \ (nt - 1) label_offset = 3 for i1, tick in enumerate(atick): x_of, y_of = -label_offset, label_offset if ax == 'y': y_of = int(-i1 * tick_step) else: x_of = int(i1 * tick_step) if draw: self.c.create_text(tick_x + x_of, tick_y + y_of, text=tick, anchor=tick_anchor) x_mini, y_mini = 0, 0 x_maxi, y_maxi = 0, 0 if ax == 'y': x_of += label_offset x_mini, x_maxi = 8, self.w - st_offset * 2 # Remember what y coord this grid line is at. if i1 == 0: self.y_grid = [] self.y_grid.append(tick_y + y_of) else: y_of -= label_offset y_mini, y_maxi = -8, st_offset * 2 - self.h # Remember what x coord this grid line is at. if i1 == 0: self.x_grid = [] self.x_grid.append(tick_x + x_of) if draw: # Draw the little solid tick, next to the axis. self.c.create_line(tick_x + x_of, tick_y + y_of, tick_x + x_of + x_mini, tick_y + y_of + y_mini) # Draw a dashed grid line, across the entire graph. self.c.create_line(tick_x + x_of, tick_y + y_of, tick_x + x_of + x_maxi, tick_y + y_of + y_maxi, dash=(1, 3)) def car_points(self, draw=True): "Plot the cars themselves." # 199 215 151 151 199 224 230 162 157 250 224 167 178 165 192 249 200 216 204 204 204 191 173 158 color_order = ['#c7d797', '#97c7e0', '#e6a29d', '#fae0a7', '#b2a5c0', '#f9c8d8', '#bfad9e', '#cccccc'] #color_order = ['#98df8a', '#dbdb8d', '#aec7e8', '#c9acd4', '#f7b6d2', # '#ffbb80', '#dc9b8d', '#e9ab17', '#dddddd'] # Those colors above aren't saturated enough. Saturate them more. color_order = map(lambda x: resaturate(x, -80), color_order) # Change color depending on year. cy = dict() for i1, year in enumerate(reversed(sorted(set(self.u.all_year)))): cy[year] = color_order[-1] if i1 < len(color_order): cy[year] = color_order[i1] i1 = -1 # Tuples of (index into self.u.all_* arrays, x position, y position). self.ov_dict = dict() if draw: self.c.focus_set() self.c.bind('<Button-1>', func=self.zoom) self.c.bind('<Button-2>', func=self.unzoom) self.c.bind('<Left>', func=self.left_key) self.c.bind('<Right>', func=self.right_key) self.c.bind('<Up>', func=self.up_key) self.c.bind('<Down>', func=self.down_key) legend = set() osz = 3 + self.zoom_level * 1 # Total vehicle count, and vehicles which pass the filter count. self.vcount = self.fcount = 0 for year, km, price in zip(self.u.all_year, self.u.all_km, self.u.all_price): x, y = self.xyp(km, price) i1 += 1 if x < self.x_grid[0] or x > self.x_grid[-1] or \ y > self.y_grid[0] or y < self.y_grid[-1]: continue self.vcount += 1 legend.add((year, cy[year])) filtered = False if not re.search(self.filter, self.u.all_descr[i1], re.I): filtered = True # If a data point is filtered out, make its outline reflect its # model year, and fill it with white. # # Else, make its outline and fill color reflect the model year, and # upon mouseover, make it entirely red. ov = self.c.create_oval(x-osz, y-osz, x+osz, y+osz, outline=cy[year], activeoutline=['red', cy[year]][filtered], fill=[cy[year], 'white'][filtered], activefill=['red', 'white'][filtered], ) self.ov_dict[ov] = (i1, x, y, cy[year], filtered) # If a data point is filtered out, mousing over it does nothing, # and also, lower it behind everything else. if filtered: self.c.lower(ov) else: self.fcount += 1 if draw: use_tag = 'Tag %d' % i1 self.c.addtag_withtag(use_tag, ov) self.c.tag_bind(use_tag, sequence='<Enter>', func=self.mouseover) self.c.tag_bind(use_tag, sequence='<Leave>', func=self.mouseoff) self.c.tag_bind(use_tag, sequence='<Button-1>', func=self.select) if draw: # OK, add a legend for every year that's displayed. i1 = 0 for yr, color in reversed(sorted(legend)): xp, yp = self.x_grid[-1] + 10, self.y_grid[-1] + 15 * i1 self.c.create_oval(xp-osz, yp-osz, xp+osz, yp+osz, outline=color, fill=color) self.c.create_text(xp + 8, yp, text=str(yr), anchor=W) i1 += 1 # And, add a title. tistr = 'Vehicle count: %d' % self.vcount if self.fcount != self.vcount: tistr = 'Filtered vehicle count: %d' % self.fcount xp = (self.x_grid[0] + self.x_grid[-1]) / 2 yp = self.y_grid[-1] - 30 self.c.create_text(xp, yp, text=tistr, font=('Helvetica', '16')) zstr1 = 'Click on a blank graph location to zoom in' zstr2 = 'Right click to zoom out' if self.zoom_level == 0: zstr = zstr1 elif self.zoom_level == 2: zstr = zstr2 else: zstr = zstr1 + ', or r' + zstr2[1:] self.c.create_text(xp, yp + 16, text=zstr, font=('Helvetica', '14')) def mouseover(self, event): oval = event.widget.find_closest(event.x, event.y)[0] # XXX Sometimes, the closest widget is an axis grid line, not an oval. # Need to handle this correctly eventually. if oval not in self.ov_dict: return self.is_hovering = True ind, x, y, color, filtered = self.ov_dict[oval] # Figure out how high the box needs to be by creating the text off- # graph, then getting its bbox and deleting it. w = 200 de_text = self.u.all_descr[ind] deobj = self.c.create_text(self.w + 3, self.h + 3, text=de_text, anchor=N+W, width=w-6, font=('Helvetica', '14')) bbox = self.c.bbox(deobj) self.c.delete(deobj) h = 18 + bbox[3] - bbox[1] border = 5 if x > self.xmid: x -= (w + border) else: x += border if y > self.ymid: y -= (h + border) else: y += border self.re = list() self.re.append(self.c.create_rectangle(x, y, x + w, y + h, fill=resaturate(color, 50))) pr_text = '$%s' % self.u.commafy(self.u.all_price[ind]) self.re.append(self.c.create_text(x + 3, y + 3, text=pr_text, anchor=N+W, font=('Helvetica', '10'))) km_text = '%skm' % self.u.commafy(self.u.all_km[ind]) self.re.append(self.c.create_text(x + w - 3, y + 3, text=km_text, anchor=N+E, font=('Helvetica', '10'))) wh_text = self.u.all_wherestr[ind] if wh_text[0].isdigit(): wh_text += ' away' self.re.append(self.c.create_text(x + w/2, y + 3, text=wh_text, anchor=N, font=('Helvetica', '10'))) self.re.append(self.c.create_text(x + 3, y + 16, text=de_text, anchor=N+W, width=w-6, font=('Helvetica', '14'))) def set_filter(self, st): "Given a string 'st', filter ovals whose description doesn't match." self.filter = st self.replot() def mouseoff(self, event): "Code for mousing off a data point." # The tooptip rectangle and all its sub-objects need to be destroyed. map(self.c.delete, self.re) # Also, need to note that we're no longer over an oval -- that way, # Button-1 events will cause a zoom, rather than launching a web page. self.is_hovering = False def _zoom_animation(self): import time from math import tanh scale = 5 for i1 in range(-scale, scale+1): self.replot(zlfrac=0.5 + 0.5*tanh(i1*2.0/scale)/tanh(2.0)) self.c.update() def zoom(self, event): # Only zoom in if we're actually within the graph boundaries. if event.x <= self.x_grid[0] or event.x > self.x_grid[-1]: return if event.y >= self.y_grid[0] or event.y < self.y_grid[-1]: return # Don't zoom if we're hovering over a data point: let the web browser # event handler operate. if self.is_hovering: return # Don't zoom in more than twice. if self.zoom_level >= 2: return # Find the grid square which we're inside. for i1 in range(len(self.x_grid) - 1): if event.x <= self.x_grid[i1 + 1]: xgrid = i1 + 1 break for i1 in range(len(self.y_grid) - 1): if event.y >= self.y_grid[i1 + 1]: ygrid = i1 + 1 break self.zoom_level += 1 zl = self.zoom_level # Make the limits of the new graph be those of the grid square which # was clicked inside. self.km[zl] = (self.xtick[xgrid-1], self.xtick[xgrid]) self.price[zl] = (self.ytick[ygrid-1], self.ytick[ygrid]) if zl == 1: self.zoom_price_start = self.u.axis(*self.price[0])[:2] self.zoom_km_start = self.u.axis(*self.km[0])[:2] else: self.zoom_price_start = self.price[zl - 1] self.zoom_km_start = self.km[zl - 1] self.zoom_price_end = self.price[zl] self.zoom_km_end = self.km[zl] self._zoom_animation() self.replot() def unzoom(self, event): # If already at maximum zoom, nothing to be done. if self.zoom_level == 0: return # If not clicking inside graph boundaries, don't unzoom. if event.x <= self.x_grid[0] or event.x > self.x_grid[-1]: return if event.y >= self.y_grid[0] or event.y < self.y_grid[-1]: return self.zoom_level -= 1 zl = self.zoom_level self.zoom_price_start = self.price[zl + 1] self.zoom_km_start = self.km[zl + 1] if zl == 0: self.zoom_price_end = self.u.axis(*self.price[0])[:2] self.zoom_km_end = self.u.axis(*self.km[0])[:2] else: self.zoom_price_end = self.price[zl] self.zoom_km_end = self.km[zl] self._zoom_animation() self.replot() def left_key(self, event): zl = self.zoom_level if zl == 0: return # If at left edge already, don't scroll. kz = self.km[zl] if self.km[0][0] > kz[0]: return self.zoom_price_start = self.zoom_price_end = self.price[zl] self.zoom_km_start = kz self.km[zl] = (kz[0] - (kz[1] - kz[0]), kz[0]) self.zoom_km_end = self.km[zl] self._zoom_animation() self.replot() def right_key(self, event): zl = self.zoom_level if zl == 0: return # If at right edge already, don't scroll. kz = self.km[zl] if self.km[0][1] < kz[1]: return self.zoom_price_start = self.zoom_price_end = self.price[zl] self.zoom_km_start = kz self.km[zl] = (kz[1], kz[1] + (kz[1] - kz[0])) self.zoom_km_end = self.km[zl] self._zoom_animation() self.replot() def down_key(self, event): zl = self.zoom_level if zl == 0: return # If at bottom edge already, don't scroll. pz = self.price[zl] if self.price[0][0] > pz[0]: return self.zoom_km_start = self.zoom_km_end = self.km[zl] self.zoom_price_start = pz self.price[zl] = (pz[0] - (pz[1] - pz[0]), pz[0]) self.zoom_price_end = self.price[zl] self._zoom_animation() self.replot() def up_key(self, event): zl = self.zoom_level if zl == 0: return # If at top edge already, don't scroll. pz = self.price[zl] if self.price[0][1] < pz[1]: return self.zoom_km_start = self.zoom_km_end = self.km[zl] self.zoom_price_start = pz self.price[zl] = (pz[1], pz[1] + (pz[1] - pz[0])) self.zoom_price_end = self.price[zl] self._zoom_animation() self.replot() def select(self, event): "Open a web page, when a data point has been clicked on." oval = event.widget.find_closest(event.x, event.y)[0] # XXX As above, sometimes the closest widget is a grid line, not an # oval. Need to handle this correctly, eventually. if oval not in self.ov_dict: return ind, xp, yp, color, filtered = self.ov_dict[oval] webbrowser.open(self.u.all_alink[ind])
class CraterViz(Tk): """ Visualization class using Tkinter to build objects and track them on a canvas """ def __init__(self, surface): Tk.__init__(self) self.title("Crater Density Visualization") self.surface = surface self.craters = {} fr = Frame(self) fr.pack() self.canvas = Canvas(fr, height = 580, width = 500) self.canvas.pack() self.init_ui() self.counter = 0; self.text_year = None self.text_craters = None #Builds canvas and adds the craters to it def init_ui(self): self._create_grid(self.canvas) self.canvas.pack() counter = 1 for crater in self.surface.get_all_craters(): self.after(counter * 100, self._add_crater, crater) counter += 1 #Creates the grid on the canvas def _create_grid(self, canvas): """ Create 10km Grid """ for i in range(50): canvas.create_line(10 * i, 0, 10 * i, 500, fill="#eee") canvas.create_line(0, 10 * i, 500, 10 * i, fill="#eee") #Adds a single crater to the map def _add_crater(self, crater): x, y = crater.get_location() outer_left = x - (25 * 1.2) outer_right = x + (25 * 1.2) outer_top = y - (25 * 1.2) outer_bottom = y + (25 * 1.2) outer = self.canvas.create_oval( outer_left, outer_top, outer_right, outer_bottom, outline="#f11", fill="#1f1", width=2) inner_left = x - 25 inner_right = x + 25 inner_top = y - 25 inner_bottom = y + 25 inner = self.canvas.create_oval( inner_left, inner_top, inner_right, inner_bottom, outline="#ccc", fill="green", width=2) craters_to_obliterate = self._find_obliterated_craters(crater) for obliterated in craters_to_obliterate: self._obliterate_crater(obliterated) self.craters[crater] = (x, y, inner, outer) self.counter += 1 self._update_hud(self.counter, len(self.craters)) #Removes crater from surface def _obliterate_crater(self, crater): x, y, inner, outer = self.craters[crater] del self.craters[crater] self.canvas.delete(inner) self.canvas.delete(outer) #Finds all Craters that need to be removed def _find_obliterated_craters(self, new_crater): obliterated_craters = [] #Check if other craters are within cover radius cover_radius = new_crater.get_covering_radius() for crater in self.craters: if cover_radius > self._get_distance(crater, new_crater): obliterated_craters.append(crater) return obliterated_craters #Gets the distance between crater centers def _get_distance(self, crater1, crater2): x1, y1 = crater1.get_location() x2, y2 = crater2.get_location() return math.sqrt((x1 - x2)**2 + (y1 - y2)**2) #Updates the heads up display on the bottom of the canvas def _update_hud(self, year, craters): if self.text_year: self.canvas.delete(self.text_year) self.text_year = self.canvas.create_text(480, 560, anchor="e", text="Year: "+str(year)+"000") if self.text_craters: self.canvas.delete(self.text_craters) self.text_craters = self.canvas.create_text(20, 560, anchor="w", text="Craters: "+str(craters))
def screen_draw(): global window, canvas_frame, canvas_play, canvas_play1, canvas_play2, canvas_future, level, point, max_point, canvas_pause level = 1 point = 0 max_point = 0 canvas_frame = Canvas(window) #,bg='red') canvas_frame.place(x=0, y=0, relwidth=1.0, relheight=1.0) global frame1, frame2 frame1 = Frame(window) frame2 = Frame(window) frame1.place(x=0, y=0, width=300, height=600) frame2.place(x=0, y=0, width=300, height=600) canvas_play1 = Canvas(frame1, bg='#000000') canvas_play1.place(x=0, y=0, width=300, height=600) for x in range(1, 10): for y in range(1, 20): canvas_play1.create_line(30 * x, 0, 30 * x, 600, fill='#111111') #,tag='play') canvas_play1.create_line(0, 30 * y, 300, 30 * y, fill='#111111') #,tag='play') canvas_play2 = Canvas(frame2, bg='#000000') canvas_play2.place(x=0, y=0, width=300, height=600) for x in range(1, 10): for y in range(1, 20): canvas_play2.create_line(30 * x, 0, 30 * x, 600, fill='#111111') canvas_play2.create_line(0, 30 * y, 300, 30 * y, fill='#111111') canvas_play = frame2 canvas_frame.create_text(370, 200, font=('Purisa', 24), text='Level', anchor='n') canvas_frame.create_text(370, 336, font=('Purisa', 24), text='Point', anchor='n') canvas_frame.create_text(370, 436, font=('Purisa', 24), text='Max', anchor='n') canvas_frame.create_text(370, 270, text=str(level), font=('', 24), fill='#0000ff', tag='level') canvas_frame.create_text(370, 400, text=str(point), font=('', 24), fill='#0000ff', tag='point') canvas_frame.create_text(370, 500, text=str(max_point), font=('', 24), fill='#ff0000', tag='max') canvas_future = Canvas(window) #,bg='#0000ff') canvas_future.place(x=310, y=10, width=120, height=120) canvas_pause = Canvas(canvas_frame) #,bg='yellow') canvas_pause.place(x=345, y=540, width=50, height=50) draw_play() canvas_pause.bind('<ButtonPress-1>', event_pause)
class carGUI: carDict = {} carIDs = [] def __init__(self, master): self.master = master master.title("A simple GUI") # Initialize Canvas self.canv = Canvas(master) self.canv.pack(fill='both', expand=True) # Initialize X-Lane self.xTop = self.canv.create_line(0, 470, 1000, 470, fill='black', tags=('top')) self.xBottom = self.canv.create_line(0, 510, 1000, 510, fill='black', tags=('left')) # Initialize Y-Lane self.yLeft = self.canv.create_line(470, 0, 470, 1000, fill='blue', tags='right') self.yRight = self.canv.create_line(510, 0, 510, 1000, fill='blue', tags='bottom') # Highlight Intersection self.rect = self.canv.create_rectangle(470, 470, 510, 510, fill='green') # Show Regulation Lines self.xLimit = self.canv.create_line(470 - 40, 450, 470 - 40, 530, fill="red") self.yLimit = self.canv.create_line(450, 470 - 40, 530, 470 - 40, fill="red") # Create button to begin simulation b = Button(text="Start Simluation!", command=self.simClickListener) b.pack() # Create checkbox to differentiate real world sim from autonomous sim self.CheckVar = IntVar() self.checkConventional = Checkbutton(text="Conventional System", variable=self.CheckVar, \ onvalue=1, offvalue=0, height=5) self.checkConventional.pack() # Create text fields to show first in queue cars self.carDisplayX = self.canv.create_text(10, 10, anchor="nw", fill="red") self.carDisplayY = self.canv.create_text(600, 10, anchor="nw", fill="black") def drawCar(self, lane, ID): if (lane == 1): # Draw an X car self.rect = self.canv.create_rectangle(0, 485, 10, 495, fill='black') elif (lane == 2): # Draw a Y car self.rect = self.canv.create_rectangle(485, 0, 495, 10, fill='red') self.canv.addtag_below(self.rect, "HELLO") # Register the ID of the car self.carIDs.append(ID) # Ad the key value pair to the car dictionary for the GUI self.carDict[ID] = self.rect def moveCars(self, carList, timeInterval): self.master.update_idletasks() # THIS UPDATES THE GUI for i in range(0, len(carList)): self.canv.move(self.carDict[carList[i].ID], carList[i].velocityX * timeInterval, carList[i].velocityY * timeInterval) def highlightCar(self, car, color): self.canv.itemconfig(self.carDict[car.ID], fill=color) def simClickListener(self): from Simulation import simulation as sim sim(self) def updateCarInformationDisplay(self, car): carData = "position X = " + str(car.positionX) + "\nposition Y = " + \ str(car.positionY) + "\nvelocity X = " + str(car.velocityX) + \ "\nvelocity Y = " + str(car.velocityY) if (car.velocityX > 0): self.canv.itemconfig(self.carDisplayX, text=carData) else: self.canv.itemconfig(self.carDisplayY, text=carData)
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
class SudokuUI(Frame): # Frame is a rectangular region on a screen """ The Tkinter UI, responsible for drawing the board and accepting user input """ def __init__(self, parent, game): self.game = game Frame.__init__(self, parent) self.parent = parent # all widgets belong to a parent self.row, self.col = -1, -1 # initialize row and col to use later self.__initUI() # calls the initUI function def __initUI(self): self.parent.title("Sudoku") # our parent window will be called Sudoku self.pack( fill=BOTH, expand=1 ) # Frame attribute, organizes geometry relative to parent, fill options: both, none, x, y self.canvas = Canvas(self, width=WIDTH, height=HEIGHT) self.canvas.pack(fill=BOTH, side=TOP) # canvas attribute, helps display our board clear_button = Button(self, text="Clear answers", command=self.__clear_answers) clear_button.pack(fill=BOTH, side=BOTTOM) # Clear button is at the bottom and fills the space self.__draw_grid() # helper functions self.__draw_puzzle() self.canvas.bind( "<Button-1>", self.__cell_clicked ) # binds Button-1 to a callback, another method: cell_clicked # in Tkinter, Button-1 is a default left mouse click self.canvas.bind("<Key>", self.__key_pressed) # binds the key (guesed number) to the key presseed method def __draw_grid( self ): # make the sudoku layout, do all private functions take self and then other potential arguments? """ Draws grid divided with blue lines into 3x3 squares """ for i in xrange(10): color = "blue" if i % 3 == 0 else "gray" # blue lines if divisible by 3 # draw vertical lines x0 = MARGIN + i * SIDE y0 = MARGIN x1 = MARGIN + i * SIDE y1 = HEIGHT - MARGIN self.canvas.create_line( x0, y0, x1, y1, fill=color ) # draw the vertical lines coordinates are (x0, y0) (x1, y1) # draw horizontal lines x0 = MARGIN y0 = MARGIN + i * SIDE x1 = WIDTH - MARGIN y1 = MARGIN + i * SIDE self.canvas.create_line(x0, y0, x1, y1, fill=color) def __draw_puzzle(self): self.canvas.delete("numbers") # delete old numbers? for i in xrange(9): for j in xrange(9): answer = self.game.puzzle[i][j] if answer != 0: x = MARGIN + j * SIDE + SIDE / 2 # in the middle of the applicable cell y = MARGIN + i * SIDE + SIDE / 2 original = self.game.start_puzzle[i][j] color = "black" if answer == original else "sea green" self.canvas.create_text(x, y, text=answer, tags="numbers", fill=color) def __draw_cursor(self): self.canvas.delete("cursor") if self.row >= 0 and self.col >= 0: # you set these variables as 0 first in init x0 = MARGIN + self.col * SIDE + 1 # what does -1 do to these variables? y0 = MARGIN + self.row * SIDE + 1 x1 = MARGIN + (self.col + 1) * SIDE - 1 y1 = MARGIN + (self.row + 1) * SIDE - 1 self.canvas.create_rectangle(x0, y0, x1, y1, outline="red", tags="cursor") def __draw_victory(self): # creates an oval/circle x0 = y0 = MARGIN + SIDE * 2 # upper left box of circle starts margin + 2 rows in x1 = y1 = MARGIN + SIDE * 7 self.canvas.create_oval(x0, y0, x1, y1, tags="victory", fill="dark orange", outline="orange") # create text x = y = MARGIN + 4 * SIDE + SIDE / 2 # middle of the circle self.canvas.create_text(x, y, text="You win!", tags="victory", fill="white", font=("Arial", 32)) def __cell_clicked(self, event): # event parameter: gives us x&y coordinates of where user clicked if self.game.game_over: return # do nothing if game is over x, y = event.x, event.y if MARGIN < x < WIDTH - MARGIN and MARGIN < y < HEIGHT - MARGIN: # if our puzzle grid is clicked self.canvas.focus_set() # focus_set: move focus to a widget # get row and col numbers from x, y coordinates row, col = (y - MARGIN) / SIDE, (x - MARGIN) / SIDE # if cell was selected already, another click should de-select it if (row, col) == (self.row, self.col): self.row, self.col = -1, -1 # I assume -1 means de-selecting? elif self.game.puzzle[row][col] == 0: # otherwise, grab corresponding cell self.row, self.col = row, col else: self.row, self.col = -1, -1 self.__draw_cursor() def __key_pressed(self, event): if self.game.game_over: return if self.row >= 0 and self.col >= 0 and event.char in "1234567890": # where does event.char come from? tkinter? self.game.puzzle[self.row][self.col] = int(event.char) self.col, self.row = -1, -1 self.__draw_puzzle() self.__draw_cursor() if self.game.check_win(): # every time you enter in a number, the game checks to see if you have won self.__draw_victory() def __clear_answers(self): self.game.start() self.canvas.delete("victory") # remove the victory circle self.__draw_puzzle()