def main(): global drawing_area root = Tk() root.title("Drawer") drawing_area = Canvas(root, width=300, height=300, bg="white") # Binding Events to the canvas drawing_area.bind("<B1-Motion>", drag) drawing_area.bind("<ButtonRelease-1>", drag_end) drawing_area.pack() # Buttons # Quit Button b1 = Button(root, text="Quit") b1.pack() b1.bind("<Button-1>", quit) # Clear Button b2 = Button(root, text="Clear") b2.pack() b2.bind("<Button-1>", clear) # Save Button b3 = Button(root, text="Save") b3.pack() b3.bind("<Button-1>", save) root.mainloop()
def __init__(self, parent, *args, **kw): Frame.__init__(self, parent, *args, **kw) vscrollbar = Scrollbar(self, orient=VERTICAL) vscrollbar.pack(fill=Y, side=RIGHT, expand=FALSE) canvas = Canvas(self, bd=0, highlightthickness=0, yscrollcommand=vscrollbar.set) canvas.pack(side=LEFT, fill=BOTH, expand=TRUE) vscrollbar.config(command=canvas.yview) canvas.xview_moveto(0) canvas.yview_moveto(0) self.interior = interior = Frame(canvas) interior_id = canvas.create_window(0, 0, window=interior, anchor=NW) self.canv = canvas # @UndefinedVariable self.scroller = vscrollbar def _configure_interior(event): size = (interior.winfo_reqwidth(), interior.winfo_reqheight()) canvas.config(scrollregion="0 0 %s %s" % size) if interior.winfo_reqwidth() != canvas.winfo_width(): canvas.config(width=interior.winfo_reqwidth()) interior.bind('<Configure>', _configure_interior) def _configure_canvas(event): if interior.winfo_reqwidth() != canvas.winfo_width(): canvas.itemconfigure(interior_id, width=canvas.winfo_width()) canvas.bind('<Configure>', _configure_canvas)
def __init__(self, parent, *args, **kw): Frame.__init__(self, parent, *args, **kw) # create a canvas object and a vertical scrollbar for scrolling it vscrollbar = Scrollbar(self, orient=VERTICAL) vscrollbar.pack(fill=Y, side=RIGHT, expand=FALSE) canvas = Canvas(self, bd=0, highlightthickness=0, yscrollcommand=vscrollbar.set) canvas.pack(side=LEFT, fill=BOTH, expand=TRUE) vscrollbar.config(command=canvas.yview) # reset the view canvas.xview_moveto(0) canvas.yview_moveto(0) # create a frame inside the canvas which will be scrolled with it self.interior = interior = Frame(canvas) interior_id = canvas.create_window(0, 0, window=interior, anchor=NW) # track changes to the canvas and frame width and sync them, # also updating the scrollbar def _configure_interior(event=None): # update the scrollbars to match the size of the inner frame size = (interior.winfo_reqwidth(), interior.winfo_reqheight()) canvas.config(scrollregion="0 0 %s %s" % size) if interior.winfo_reqwidth() != canvas.winfo_width(): # update the canvas's width to fit the inner frame canvas.config(width=interior.winfo_reqwidth()) interior.bind('<Configure>', _configure_interior) def _configure_canvas(event=None): if interior.winfo_reqwidth() != canvas.winfo_width(): # update the inner frame's width to fill the canvas canvas.itemconfigure(interior_id, width=canvas.winfo_width()) canvas.bind('<Configure>', _configure_canvas)
def main(): global drawing_area root = Tk() root.title("Drawer") drawing_area = Canvas(root, width=300, height=300, bg="white") # Binding Events to the canvas drawing_area.bind("<B1-Motion>", drag) drawing_area.bind("<ButtonRelease-1>", drag_end) drawing_area.pack() #Buttons #Quit Button b1 = Button(root, text="Quit") b1.pack() b1.bind("<Button-1>", quit) #Clear Button b2 = Button(root, text="Clear") b2.pack() b2.bind("<Button-1>", clear) #Save Button b3 = Button(root, text="Save") b3.pack() b3.bind("<Button-1>", save) root.mainloop()
def __scrubber(self, master): sc = Canvas( master, width=800, height=SCRUBBER_HEIGHT, background="white", ) def sc_goto(e): width_fraction = float(e.x) / sc.winfo_width() ev_s = self.get_earliest_bookmark_after(0) ev_e = self.get_latest_bookmark_before(sys.maxint) ev_l = ev_e - ev_s self.render_start.set(ev_s + ev_l * width_fraction - float(self.render_len.get()) / 2) if not self.render_auto.get(): self.update() self.canvas.xview_moveto(0.5) sc.bind("<1>", sc_goto) def resize(event): if self.c: self.render_scrubber_activity() self.render_scrubber_arrow() # sc.coords(line, 0, 0, event.width, event.height) sc.bind("<Configure>", resize) return sc
def __init__(self, parent, *args, **kw): Frame.__init__(self, parent, *args, **kw) vscrollbar = Scrollbar(self, orient=VERTICAL) vscrollbar.pack(fill=Y, side=RIGHT, expand=FALSE) canvas = Canvas( self, bd=0, highlightthickness=0, yscrollcommand=vscrollbar.set) canvas.pack(side=LEFT, fill=BOTH, expand=TRUE) vscrollbar.config(command=canvas.yview) canvas.xview_moveto(0) canvas.yview_moveto(0) self.interior = interior = Frame(canvas) interior_id = canvas.create_window(0, 0, window=interior, anchor=NW) self.canv = canvas # @UndefinedVariable self.scroller = vscrollbar def _configure_interior(event): size = (interior.winfo_reqwidth(), interior.winfo_reqheight()) canvas.config(scrollregion="0 0 %s %s" % size) if interior.winfo_reqwidth() != canvas.winfo_width(): canvas.config(width=interior.winfo_reqwidth()) interior.bind('<Configure>', _configure_interior) def _configure_canvas(event): if interior.winfo_reqwidth() != canvas.winfo_width(): canvas.itemconfigure(interior_id, width=canvas.winfo_width()) canvas.bind('<Configure>', _configure_canvas)
class MarcaFoto(Frame): def __init__(self, root): Frame.__init__(self, root) self.grid(column=0, row=0) self.canvas = Canvas(self, width=604, height=480) self.canvas.grid(column=0, row=0, columnspan=2) self.coords = Label(self) self.coords.grid(column=0, row=1) nome_arq_foto = 'turma1-640x480.gif' self.foto = PhotoImage(file=nome_arq_foto) self.canvas.create_image(0, 0, image=self.foto, anchor=NW) self.canvas.bind('<Motion>', self.moveu) self.canvas.bind('<ButtonPress>', self.marcar) self.marca_ativa = None def moveu(self, evento): if self.marca_ativa is not None: bbox = self.canvas.coords(self.marca_ativa) bbox[2:4] = [evento.x, evento.y] self.canvas.coords(self.marca_ativa, *bbox) def marcar(self, evento): if self.marca_ativa is None: self.marca_ativa = self.canvas.create_oval(evento.x, evento.y, evento.x, evento.y, outline='green', width=5) else: coords = [int(i) for i in self.canvas.coords(self.marca_ativa)] self.coords['text'] = coords print coords self.marca_ativa = None
class View(Observer): def __init__(self,parent,subject,bg="white"): print("View : __init__") Observer.__init__(self) self.subject=subject self.parent=parent self.signal_id=None self.canvas=Canvas(parent,bg=bg) self.canvas.bind("<Configure>", self.resize) self.width=int(self.canvas.cget("width")) self.height=int(self.canvas.cget("height")) def update(self,subject): print("View : update") signal=subject.get_signal() self.signal_id=self.plot_signal(signal) def plot_signal(self,signal,color="red"): width,height=self.width,self.height if self.signal_id!=None : self.canvas.delete(self.signal_id) if signal and len(signal)>1: plot=[(x*width, height/2.0*(y+1)) for (x, y) in signal] self.signal_id=self.canvas.create_line(plot,fill=color,smooth=1,width=3) return self.signal_id def resize(self, event): """ En cas de reconfiguration de fenetre """ if event: self.width = event.width self.height = event.height ## self.width = int(event.widget.cget("width")) ## self.height = int(event.widget.cget("height")) ## print("View : resize cget",event.widget.cget("width"),event.widget.cget("height")) print("View : resize event",event.width,event.height) self.canvas.delete("grid") self.plot_signal(self.subject.get_signal()) self.grid() def grid(self, steps=8): width,height=self.width,self.height # self.canvas.create_line(10,height/2,width,height/2,arrow="last",tags="grid") # self.canvas.create_line(10,height-5,10,5,arrow="last",tags="grid") step=width/steps*1. for t in range(1,steps+2): x =t*step self.canvas.create_line(x,0,x,height,tags="grid") self.canvas.create_line(0,x,width,x,tags="grid") self.canvas.create_line(x,height/2-4,x,height/2+4,tags="grid") def packing(self) : self.canvas.pack(expand=1,fill="both",padx=6)
def initUI(self): self.b1up = True drawing_area = Canvas(self.parent, width=self.table_width, height=self.table_height) drawing_area.pack(fill=BOTH, expand=1) drawing_area.xview("moveto", 0) # http://tcl.sourceforge.net/faqs/tk/#canvas/border drawing_area.yview("moveto", 0) drawing_area.bind("<Motion>", self.h_motion) drawing_area.bind("<ButtonPress-1>", self.h_b1down) drawing_area.bind("<ButtonRelease-1>", self.h_b1up) self.drawing_area = drawing_area self.pack(fill=BOTH, expand=1)
class Lissajou(Observer): def __init__(self, parent,subjects,bg="black"): self.subjects=subjects self.canvas=Canvas(parent,bg=bg) self.width = int(self.canvas.cget("width")) self.height = int(self.canvas.cget("height")) self.signalXY_id = None self.canvas.bind("<Configure>", self.resize) self.packing() def update(self): print("Lissajou update") self.signalXY_id = self.plot_lissajou() def resize(self, event): if event: self.width=event.width self.height=event.height self.grid() self.update() def grid(self, n=10, m=10,color="white"): self.canvas.delete("all") w,h=self.width,self.height width,height=int(w),int(h) self.canvas.create_line(n,(height/2.0),width,(height/2.0),arrow="last",fill=color) self.canvas.create_line(width/2.0,height,width/2.0,5.0,arrow="last",fill=color) stepX=(width)/m*1.0 stepY=(height)/n*1.0 for t in range(1,m+1): x =t*stepX self.canvas.create_line(x,height,x,20,fill=color) for t in range(1,n+1): y =t*stepY self.canvas.create_line(10.0,y,width-10,y,fill=color) def plot_lissajou(self,color='green'): width,height=int(self.width-12),int(self.height) signalXY = self.subjects.getSignalXY() if signalXY!=None: self.canvas.delete(self.signalXY_id) if signalXY and len(signalXY)>1: plot=[((x+1)*(width/2)+5, height/2.0*(y+1)) for (x, y) in signalXY] signalValue = self.canvas.create_line(plot, fill=color, smooth=1, width=2) return signalValue def packing(self): self.canvas.pack(expand=1, fill='both',side='top')
class JoystickFrame(LabelFrame): def __init__(self, master, tracker, text="Joystick", **options): LabelFrame.__init__(self, master, text=text, **options) self.tracker = tracker self.width = 400 self.height = 400 self.canvas = Canvas(self, height=self.height, width=self.width) self.canvas.grid() self.canvas.create_oval((self.width/2 - 3, self.height/2 - 3, self.width/2 + 3, self.height/2 + 3)) self.canvas.bind("<Button-1>", bg_caller(lambda event: self.move_tracker(event))) self.canvas.bind("<Motion>", self.update_label) self.motion_label = Label(self, text="", font=tkFont.Font(family="Courier")) self.motion_label.grid() f = LabelFrame(self, text="Sensitivity") self.sensitivity_scale = Scale(f, from_=0, to=10, resolution=0.01, orient=HORIZONTAL, length=self.width) self.sensitivity_scale.set(5) self.sensitivity_scale.grid() f.grid() @property def sensitivity(self): return self.sensitivity_scale.get() / 2000. def get_delta(self, event): dx = event.x - int(self.canvas['width'])/2. dy = event.y - int(self.canvas['height'])/2. dx_rad = dx*self.sensitivity dy_rad = dy*self.sensitivity dtheta = dy_rad dphi = -dx_rad return (dtheta, dphi) def update_label(self, event): dtheta, dphi = self.get_delta(event) self.motion_label.configure(text="<{:8.5f}, {:8.5f}>".format(dtheta, dphi)) def move_tracker(self, event): dtheta, dphi = self.get_delta(event) self.tracker.move(0, dtheta, dphi) logger.info("Moved tracker by ({}, {})".format(dtheta, dphi))
def init_ui(self): self.rowconfigure(3, weight=1) self.columnconfigure(0, weight=1) self.button_load_type = Button(self, text="Load Type JSON", command=lambda: browse_file(self, 1, )) self.button_load_type.grid( row=0, columnspan=2, sticky=W + E, pady=4, padx=5) self.button_load_color = Button( self, text="Load Color JSON", command=lambda: browse_file(self, 2)) self.button_load_color.grid( row=1, columnspan=2, sticky=W + E, pady=4, padx=5) button_load = Button( self, text="Load Images", command=lambda: browse_images(self)) button_load.grid(row=2, columnspan=2, sticky=W + E, pady=4, padx=5) button_learn = Button( self, text="Test", command= lambda: start_testing(self.dtype, self.dcolor, self.picture_frames) ) button_learn.grid(row=4, columnspan=2, sticky=W + E, pady=4, padx=5) canvas = Canvas(self) canvas.grid(row=3, sticky=W + E + N + S, column=0, pady=4, padx=5) frame = self.picture_frame = Frame(canvas) canvas.create_window(0, 0, window=frame, anchor='nw') scroll_bar = Scrollbar(self, orient="vertical", command=canvas.yview) scroll_bar.grid(sticky=E + N + S, padx=5, row=3, column=1) canvas.configure(yscrollcommand=scroll_bar.set) # track changes to the canvas and frame width and sync them, # also updating the scrollbar def _configure_interior(event): # update the scrollbars to match the size of the inner frame size = (frame.winfo_reqwidth(), frame.winfo_reqheight()) canvas.config(scrollregion="0 0 %s %s" % size) if frame.winfo_reqwidth() != canvas.winfo_width(): # update the canvas's width to fit the inner frame canvas.config(width=frame.winfo_reqwidth()) frame.bind('<Configure>', _configure_interior) def _configure_canvas(event): if frame.winfo_reqwidth() != canvas.winfo_width(): # update the inner frame's width to fill the canvas canvas.itemconfigure(frame, width=canvas.winfo_width()) canvas.bind('<Configure>', _configure_canvas)
class ScrolledCanvas: def __init__(self, master, **opts): if not opts.has_key('yscrollincrement'): opts['yscrollincrement'] = 17 self.master = master self.frame = Frame(master) self.frame.rowconfigure(0, weight=1) self.frame.columnconfigure(0, weight=1) self.canvas = Canvas(self.frame, **opts) self.canvas.grid(row=0, column=0, sticky="nsew") self.vbar = Scrollbar(self.frame, name="vbar") self.vbar.grid(row=0, column=1, sticky="nse") self.hbar = Scrollbar(self.frame, name="hbar", orient="horizontal") self.hbar.grid(row=1, column=0, sticky="ews") self.canvas['yscrollcommand'] = self.vbar.set self.vbar['command'] = self.canvas.yview self.canvas['xscrollcommand'] = self.hbar.set self.hbar['command'] = self.canvas.xview self.canvas.bind("<Key-Prior>", self.page_up) self.canvas.bind("<Key-Next>", self.page_down) self.canvas.bind("<Key-Up>", self.unit_up) self.canvas.bind("<Key-Down>", self.unit_down) #if isinstance(master, Toplevel) or isinstance(master, Tk): self.canvas.bind("<Alt-Key-2>", self.zoom_height) self.canvas.focus_set() def page_up(self, event): self.canvas.yview_scroll(-1, "page") return "break" def page_down(self, event): self.canvas.yview_scroll(1, "page") return "break" def unit_up(self, event): self.canvas.yview_scroll(-1, "unit") return "break" def unit_down(self, event): self.canvas.yview_scroll(1, "unit") return "break" def zoom_height(self, event): ZoomHeight.zoom_height(self.master) return "break"
def __canvas(self, master): f = Frame(master) f.grid_columnconfigure(0, weight=1) f.grid_rowconfigure(0, weight=1) h = Scrollbar(f, orient=HORIZONTAL) v = Scrollbar(f, orient=VERTICAL) canvas = Canvas( f, background="white", xscrollcommand=h.set, yscrollcommand=v.set, ) h['command'] = canvas.xview v['command'] = canvas.yview canvas.bind("<4>", lambda e: self.scale_view(e, 1.0 * 1.1)) canvas.bind("<5>", lambda e: self.scale_view(e, 1.0 / 1.1)) # in windows, mouse wheel events always go to the root window o_O self.master.bind("<MouseWheel>", lambda e: self.scale_view( e, ((1.0 * 1.1) if e.delta > 0 else (1.0 / 1.1)) )) # Drag based movement # def _sm(e): # self.st = self.render_start.get() # self.sx = e.x # self.sy = e.y # def _cm(e): # self.render_start.set(self.st + float(self.sx - e.x)/self.scale.get()) # self.render() # self.canvas.bind("<1>", _sm) # self.canvas.bind("<B1-Motion>", _cm) canvas.grid(column=0, row=0, sticky=(N, W, E, S)) v.grid(column=1, row=0, sticky=(N, S)) h.grid(column=0, row=1, sticky=(W, E)) self.canvas = canvas return f
def createCanvas( self ): "Create and return our scrolling canvas frame." f = Frame( self ) canvas = Canvas( f, width=self.cwidth, height=self.cheight, bg=self.bg ) # Scroll bars xbar = Scrollbar( f, orient='horizontal', command=canvas.xview ) ybar = Scrollbar( f, orient='vertical', command=canvas.yview ) canvas.configure( xscrollcommand=xbar.set, yscrollcommand=ybar.set ) # Resize box resize = Label( f, bg='white' ) # Layout canvas.grid( row=0, column=1, sticky='nsew') ybar.grid( row=0, column=2, sticky='ns') xbar.grid( row=1, column=1, sticky='ew' ) resize.grid( row=1, column=2, sticky='nsew' ) # Resize behavior f.rowconfigure( 0, weight=1 ) f.columnconfigure( 1, weight=1 ) f.grid( row=0, column=0, sticky='nsew' ) f.bind( '<Configure>', lambda event: self.updateScrollRegion() ) # Mouse bindings canvas.bind( '<ButtonPress-1>', self.clickCanvas ) canvas.bind( '<B1-Motion>', self.dragCanvas ) canvas.bind( '<ButtonRelease-1>', self.releaseCanvas ) return f, canvas
def test(): global vid, canvas vid = imageio.get_reader( r'C:\Users\ohadassi\PycharmProjects\untitled\test.mp4', 'ffmpeg') master = Tk() canvas = Canvas(master) canvas.pack() canvas.bind("<1>", lambda event: canvas.focus_set()) canvas.bind('n', nextFrame) canvas.bind('p', prevFrame) canvas.bind('<B1-Motion>', motion) canvas.bind('<1>', press) nextFrame(None) mainloop()
class ScrolledCanvas: def __init__(self, master, **opts): if 'yscrollincrement' not in opts: opts['yscrollincrement'] = 17 self.master = master self.frame = Frame(master) self.frame.rowconfigure(0, weight=1) self.frame.columnconfigure(0, weight=1) self.canvas = Canvas(self.frame, **opts) self.canvas.grid(row=0, column=0, sticky="nsew") self.vbar = Scrollbar(self.frame, name="vbar") self.vbar.grid(row=0, column=1, sticky="nse") self.hbar = Scrollbar(self.frame, name="hbar", orient="horizontal") self.hbar.grid(row=1, column=0, sticky="ews") self.canvas['yscrollcommand'] = self.vbar.set self.vbar['command'] = self.canvas.yview self.canvas['xscrollcommand'] = self.hbar.set self.hbar['command'] = self.canvas.xview self.canvas.bind("<Key-Prior>", self.page_up) self.canvas.bind("<Key-Next>", self.page_down) self.canvas.bind("<Key-Up>", self.unit_up) self.canvas.bind("<Key-Down>", self.unit_down) #if isinstance(master, Toplevel) or isinstance(master, Tk): self.canvas.bind("<Alt-Key-2>", self.zoom_height) self.canvas.focus_set() def page_up(self, event): self.canvas.yview_scroll(-1, "page") return "break" def page_down(self, event): self.canvas.yview_scroll(1, "page") return "break" def unit_up(self, event): self.canvas.yview_scroll(-1, "unit") return "break" def unit_down(self, event): self.canvas.yview_scroll(1, "unit") return "break" def zoom_height(self, event): ZoomHeight.zoom_height(self.master) return "break"
def __init__(self, master, app): Frame.__init__(self, master) self.app = app self.proxy = app.proxy self.config(background=factory.bg()) canvas = Canvas(self, width=gconfig["graph-width"], height=gconfig["graph-height"], background=gconfig["graph-fill"]) self.canvas = canvas info_canvas = InfoCanvas(self) self.info_canvas = info_canvas info_canvas.grid(row=0, column=0, rowspan=1, columnspan=1, sticky='wns') canvas.grid(row=0, column=1, rowspan=1, columnspan=1, sticky='nsew') self.grid_rowconfigure(0, weight=1) self.grid_rowconfigure(1, weight=0) self.grid_columnconfigure(0, weight=0) self.grid_columnconfigure(1, weight=1) # toolbar buttons def tbutton(col, text, command=None): bwidth = 75 b = factory.button(self.canvas, text, command=command) y0 = 15 x0 = 15 x = x0 + col * bwidth b.place(x=x, y=y0, width=bwidth) tbutton(0, 'sync', self.sync) tbutton(1, '+Audio', self.add_audio_bus) tbutton(2, "+Control", self.add_control_bus) tbutton(3, "Align", self.allign_tokens) self.synth_tokens = {} # map [sid] -> SynthToken self.audio_bus_tokens = {} # map [bus-name] -> BusToken self.control_bus_tokens = {} self.current_token_and_port = None # (token,port) dragdrop source self.current_allied_ports = [] self._drag_data = { 'x': 0, 'y': 0, 'anchor-x': 0, 'anchor-y': 0, 'port1': None, #'port2' : None, 'rubberband': None } canvas.bind("<B1-Motion>", self.bus_drag) canvas.bind("<ButtonPress-1>", self.bus_drag_pickup) canvas.bind("<ButtonRelease-1>", self.bus_drop)
def __init__(self, master, app): Frame.__init__(self, master) self.app = app self.proxy = app.proxy self.config(background=factory.bg()) canvas = Canvas(self, width=gconfig["graph-width"], height=gconfig["graph-height"], background=gconfig["graph-fill"]) self.canvas = canvas info_canvas = InfoCanvas(self) self.info_canvas = info_canvas info_canvas.grid(row=0,column=0,rowspan=1,columnspan=1, sticky='wns') canvas.grid(row=0,column=1,rowspan=1,columnspan=1, sticky='nsew') self.grid_rowconfigure(0, weight=1) self.grid_rowconfigure(1, weight=0) self.grid_columnconfigure(0, weight=0) self.grid_columnconfigure(1, weight=1) # toolbar buttons def tbutton(col, text, command=None): bwidth=75 b = factory.button(self.canvas, text,command=command) y0 = 15 x0 = 15 x = x0+col*bwidth b.place(x=x,y=y0,width=bwidth) tbutton(0, 'sync', self.sync) tbutton(1, '+Audio', self.add_audio_bus) tbutton(2, "+Control", self.add_control_bus) tbutton(3, "Align", self.allign_tokens) self.synth_tokens = {} # map [sid] -> SynthToken self.audio_bus_tokens = {} # map [bus-name] -> BusToken self.control_bus_tokens = {} self.current_token_and_port = None # (token,port) dragdrop source self.current_allied_ports = [] self._drag_data = {'x': 0, 'y': 0, 'anchor-x' : 0, 'anchor-y' : 0, 'port1' : None, #'port2' : None, 'rubberband' : None} canvas.bind("<B1-Motion>", self.bus_drag) canvas.bind("<ButtonPress-1>", self.bus_drag_pickup) canvas.bind("<ButtonRelease-1>", self.bus_drop)
class SimulationCanvas( object ): """A canvas where blocks can be dragged around and connected up""" size = ( width, height ) = ( 550, 300 ) def __init__( self, frame ): # Create the canvas self.canvas = Canvas( frame, width=self.width, height=self.height, relief=RIDGE, background=colours["background"], borderwidth=1 ) # Add event handlers for dragable items self.canvas.tag_bind ( "DRAG", "<ButtonPress-1>", self.mouse_down ) #self.canvas.tag_bind ("DRAG", "<ButtonRelease-1>", self.mouse_release) self.canvas.tag_bind ( "DRAG", "<Enter>", self.enter ) self.canvas.tag_bind ( "DRAG", "<Leave>", self.leave ) self.canvas.pack( side=TOP ) # Some default locations self.PREVIEW_WIDTH = 80 self.PREVIEW_LOCATION = ( self.PREVIEW_X, self.PREVIEW_Y ) = ( 15, 30 ) # Draw a "preview" area self.canvas.create_line( self.PREVIEW_WIDTH, 0, self.PREVIEW_WIDTH, self.height, dash=True ) # A dict indexed by unique ID of elements in the canvas. self.blocks = {} def preview_actor( self, codefile ): """ Display a preview of an actor or compisite actor in the canvas, it will be dragable into desired position """ logging.debug( "Creating a preview of %(name)s on simulation canvas." % {'name':codefile.name} ) logging.debug( "Deleting any existing items still tagged 'preview'" ) self.canvas.delete( "preview" ) block = CanvasBlock( self.canvas, codefile, *self.PREVIEW_LOCATION ) self.blocks[block.id] = block def mouse_down( self, event ): logging.debug( "The mouse was pressed at (%d, %d)" % ( event.x, event.y ) ) logging.debug( "The mouse went down on a block. Binding mouse release..." ) selected = self.canvas.gettags( "current" ) logging.debug( "Currently selected items tags are %s" % selected.__repr__() ) self.selected_name = [tag for tag in selected if tag.startswith( "name:" ) ][0][5:] self.selected_id = [tag for tag in selected if tag.startswith( "id:" ) ][0][3:] self.selected_type = [tag for tag in selected if tag.startswith( "type:" ) ][0][5:] logging.debug( "Block selected was %s with id:%s" % ( self.selected_name, self.selected_id ) ) #self.canvas.addtag( 'Selected', 'withtag', self.selected_id ) logging.debug( "Current blocks are: %s" % self.blocks ) #self.blocks[block_id].set_colour( colours['selected'] ) if self.selected_type == "block" or self.selected_type == "text": self.blocks[self.selected_id].select(event.x, event.y) self.canvas.bind( "<ButtonRelease-1>", self.block_move_mouse_release ) elif self.selected_type.startswith("input") or self.selected_type.startswith("output"): self.blocks[self.selected_id].select_port(self.selected_type) self.canvas.bind( "<ButtonRelease-1>", self.port_connect_mouse_release ) else: logging.info("Tried to select %s" % self.selected_type) def block_move_mouse_release( self, event ): logging.debug( "The mouse was released at (%d, %d)" % ( event.x, event.y ) ) self.canvas.bind( "<ButtonRelease-1>", lambda e: None ) if event.x >= 0 and event.x <= self.canvas.winfo_width() \ and event.y >= 0 and event.y <= self.canvas.winfo_height(): logging.debug( "Valid move inside canvas. Relocating block." ) self.blocks[self.selected_id].move_to(event.x, event.y) if event.x >= self.PREVIEW_WIDTH: if self.blocks[self.selected_id].is_preview(): logging.info( "Moved out of preview zone, adding new component to model" ) #TODO HERE - add to model compiler or what ever... self.blocks[self.selected_id].unselect() else: self.blocks[self.selected_id].preview() else: logging.info( "Invalid move." ) def port_connect_mouse_release( self, event ): logging.debug( "The mouse was released at (%d, %d)" % ( event.x, event.y ) ) self.canvas.bind( "<ButtonRelease-1>", lambda e: None ) if event.x >= 0 and event.x <= self.canvas.winfo_width() \ and event.y >= 0 and event.y <= self.canvas.winfo_height(): logging.debug( "Valid location inside canvas." ) event.widget.itemconfigure( "Selected", fill="#000000" ) event.widget.itemconfigure( "type:text", fill="#000000" ) #block = self.canvas.gettags("Selected") #logging.debug("Block moved was made up of these components: %s" % block.__repr__()) self.canvas.dtag( "Selected", "Selected" ) else: logging.info( "Invalid wiring." ) def enter( self, event ): logging.debug( "Enter" ) def leave( self, event ): logging.debug( "Leaving" )
class Scrolling_Area(Frame, object): def __init__(self, master, width=None, anchor=N, height=None, mousewheel_speed = 2, scroll_horizontally=True, xscrollbar=None, scroll_vertically=True, yscrollbar=None, outer_background=None, inner_frame=Frame, **kw): Frame.__init__(self, master, class_=self.__class__) if outer_background: self.configure(background=outer_background) self.grid_columnconfigure(0, weight=1) self.grid_rowconfigure(0, weight=1) self._width = width self._height = height self.canvas = Canvas(self, background=outer_background, highlightthickness=0, width=width, height=height) self.canvas.grid(row=0, column=0, sticky=N+E+W+S) if scroll_vertically: if yscrollbar is not None: self.yscrollbar = yscrollbar else: self.yscrollbar = Scrollbar(self, orient=VERTICAL) self.yscrollbar.grid(row=0, column=1,sticky=N+S) self.canvas.configure(yscrollcommand=self.yscrollbar.set) self.yscrollbar['command']=self.canvas.yview else: self.yscrollbar = None if scroll_horizontally: if xscrollbar is not None: self.xscrollbar = xscrollbar else: self.xscrollbar = Scrollbar(self, orient=HORIZONTAL) self.xscrollbar.grid(row=1, column=0, sticky=E+W) self.canvas.configure(xscrollcommand=self.xscrollbar.set) self.xscrollbar['command']=self.canvas.xview else: self.xscrollbar = None self.rowconfigure(0, weight=1) self.columnconfigure(0, weight=1) self.innerframe = inner_frame(self.canvas, **kw) self.innerframe.pack(anchor=anchor) self.canvas.create_window(0, 0, window=self.innerframe, anchor='nw', tags="inner_frame") self.canvas.bind('<Configure>', self._on_canvas_configure) Mousewheel_Support(self).add_support_to(self.canvas, xscrollbar=self.xscrollbar, yscrollbar=self.yscrollbar) @property def width(self): return self.canvas.winfo_width() @width.setter def width(self, width): self.canvas.configure(width= width) @property def height(self): return self.canvas.winfo_height() @height.setter def height(self, height): self.canvas.configure(height = height) def set_size(self, width, height): self.canvas.configure(width=width, height = height) def _on_canvas_configure(self, event): width = max(self.innerframe.winfo_reqwidth(), event.width) height = max(self.innerframe.winfo_reqheight(), event.height) self.canvas.configure(scrollregion="0 0 %s %s" % (width, height)) self.canvas.itemconfigure("inner_frame", width=width, height=height) def update_viewport(self): self.update() window_width = self.innerframe.winfo_reqwidth() window_height = self.innerframe.winfo_reqheight() if self._width is None: canvas_width = window_width else: canvas_width = min(self._width, window_width) if self._height is None: canvas_height = window_height else: canvas_height = min(self._height, window_height) self.canvas.configure(scrollregion="0 0 %s %s" % (window_width, window_height), width=canvas_width, height=canvas_height) self.canvas.itemconfigure("inner_frame", width=window_width, height=window_height)
eye_left = c.create_oval(130, 110, 160, 170, outline='black', fill='white') eye_right = c.create_oval(230, 110, 260, 170, outline='black', fill='white') pupil_left = c.create_oval(140,145,150, 155, outline='black', fill='black') pupil_right = c.create_oval(240, 145, 250, 155, outline='black',fill='black') #Normal mouth mouth_normal = c.create_line(170, 250, 200, 282, 230, 250, smooth=1, width=2, state=NORMAL) #Petting face mouth_happy = c.create_line(170, 250, 200, 292, 230, 250, smooth=1, width=2, state=HIDDEN) blush_left = c.create_oval(70, 180, 120, 230, outline='hotpink', fill='hotpink', state=HIDDEN) blush_right = c.create_oval(280, 180, 330, 230, outline='hotpink', fill='hotpink', state=HIDDEN) #Sad face mouth_sad = c.create_line(170, 250, 200, 232, 230, 250, smooth=1, width=2,state=HIDDEN) #Tongue tongue_main = c.create_rectangle(170, 250, 230, 290, outline='deeppink', fill='deeppink', state=HIDDEN) tongue_tip = c.create_oval(170, 285, 230, 300, outline='deeppink', fill='deeppink', state=HIDDEN) c.pack() #Animations c.bind('<Motion>', show_happy) c.bind('<Leave>', hide_happy) c.bind('<Double-1>', cheeky) c.eyes_crossed = False c.tongue_out = False root.after(1000, blink) root.mainloop()
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 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()
class main: def __init__ (self): self.app = Tk() self.app.title('Tic Tac Toe') #self.app.resizable(width=False, height=False) #width and hight of window w = 900 h = 1100 #width and hight of screen ws = self.app.winfo_screenwidth() hs = self.app.winfo_screenheight() #calculate position x = ws/2 - w/2 y = hs/2 - h/2 #place window -> pramaters(visina, dolzina, pozicija x, pozicija y) self.app.geometry("%dx%d+%d+%d" % (w,h, x, y)) #====================================== self.frame = Frame() #main frame self.frame.pack(fill = 'both', expand = True) self.label = Label(self.frame, text = 'Tic Tac Toe', height = 4, bg = 'white', fg = 'blue') self.label.pack(fill='both', expand = True) #self.label2 = Label(self.frame, text = 'here', height = 2, bg = 'white', fg = 'blue') odkomentiri samo za develop------------- #self.label2.pack(fill='both', expand = True) self.canvas = Canvas(self.frame, width = 900, height = 900) self.canvas.pack(fill = 'both', expand = True) self.framepod = Frame(self.frame)#sub frame self.framepod.pack(fill = 'both', expand = True) self.Single = Button(self.framepod, text = 'Start single player', height = 4, command = self.startsingle, bg = 'white', fg = 'blue') self.Single.pack(fill='both', expand = True, side=RIGHT) self.Multi = Button(self.framepod, text = 'Start double player', height = 4, command = self.double, bg = 'white', fg = 'blue') self.Multi.pack(fill='both', expand = True, side=RIGHT) self.board = AI() self.draw() def double(self): #cleans the all simbols from canvas self.canvas.delete(ALL) self.label['text'] = ('Tic Tac Toe Game') self.canvas.bind("<ButtonPress-1>", self.place) self.draw() #--------------------------------------- self.table=[[-1,-1,-1],[-1,-1,-1],[-1,-1,-1]] self.c=0 #counter self.e=False #flag for end game def draw(self): #draws the outline lines self.canvas.create_rectangle(0,0,900,900, outline='black') self.canvas.create_rectangle(300,900,600,0, outline='black') self.canvas.create_rectangle(0,300,900,600, outline='black') def place(self, event): for i in range(0,900,300): for j in range(0,900,300): if event.x in range(i,i+300) and event.y in range(j, j+300): if self.canvas.find_enclosed(i,j,i+300, j+300) == (): if self.c % 2 == 0: #calculate points to draw circle x=(2*i+300)/2 y=(2*j+300)/2 x2=int(i/300) y2=int(j/300) self.canvas.create_oval(x+75,y+75,x-75,y-75, width = 4, outline="blue") self.table[y2][x2] = 4 self.c+=1 else: #calculate points to draw cross x=(2*i+300)/2 y=(2*j+300)/2 x2=int(i/300) y2=int(j/300) self.canvas.create_line(x+60,y+60,x-60,y-60, width = 4, fill="red") self.canvas.create_line(x-60,y+60,x+60,y-60, width = 4, fill="red") self.table[y2][x2] = 1 self.c+=1 self.check() def startsingle(self): self.canvas.delete(ALL) self.label['text'] = ('Tic Tac Toe Game') self.canvas.bind("<ButtonPress-1>", self.placeone) self.draw() self.board = AI() def placeone(self, event): player = 'X' for i in range(0,900,300): for j in range(0,900,300): if event.x in range(i,i+300) and event.y in range(j, j+300): if self.canvas.find_enclosed(i,j,i+300, j+300) == (): x=(2*i+300)/2 y=(2*j+300)/2 x2=int(i/300) y2=int(j/300) self.canvas.create_line(x+60,y+60,x-60,y-60, width = 4, fill="red") self.canvas.create_line(x-60,y+60,x+60,y-60, width = 4, fill="red") player_move = x2 + 3*y2 #spremeni self.board.make_move(player_move, player) if self.board.complete(): self.label['text'] = (self.board.winner()) self.canvas.unbind("ButtonPress-1") self.board = AI() elif self.board.winner() != None: self.label['text'] = (self.board.winner()) self.canvas.unbind("ButtonPress-1") self.board = AI() else: player = self.board.get_enemy(player) computer_move = self.board.determine(self.board, player) self.board.make_move(computer_move, player) ti = computer_move % 3 tj = computer_move / 3 x=(600*ti+300)/2 y=(600*tj+300)/2 #self.label2['text'] = str(computer_move) + ' ti ' + str(ti) + ' tj ' + str(tj) + ' y ' + str(y) + ' x ' +str(x) self.canvas.create_oval(x+75,y+75,x-75,y-75, width = 4, outline="blue") if self.board.winner() != None: self.label['text'] = (self.board.winner()) self.canvas.unbind("ButtonPress-1") self.board = AI() def check(self): #checks for win #horitontal for i in range(3): if sum(self.table[i])==3: self.label['text'] = ('X wins') self.end() if sum(self.table[i])==12: self.label['text'] = ('O wins') self.end() #vertical self.vs=[[row[i] for row in self.table] for i in range(3)] for i in range(3): if sum(self.vs[i])==3: self.label['text'] = ('X wins') self.end() if sum(self.vs[i])==12: self.label['text'] = ('O wins') self.end() #diagonals self.dig1=0 self.dig2=0 for i in range(3): self.dig1+=self.table[i][i] for i in range(3): self.dig2+=self.table[2-i][i] if self.dig1==3: self.label['text'] = ('X wins') self.end() if self.dig1==12: self.label['text'] = ('O wins') self.end() if self.dig2==3: self.label['text'] = ('X wins') self.end() if self.dig2==12: self.label['text'] = ('O wins') self.end() #draw if self.e==False: a=0 for i in range(3): a+=sum(self.table[i]) if a == 24: #5 *4 + 4 * 1 --> 5 circles and 4 crosses self.label['text'] = ('Draw') self.end() def end(self): self.canvas.unbind("<ButtonPress-1>") self.e=True def mainloop(self): self.app.mainloop()
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, expand=1) self.canvas = Canvas( self, width=WIDTH, height=HEIGHT, highlightthickness=0 ) 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 squares 3x3 """ 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.answer[i][j] if answer != 0: x = MARGIN + j * SIDE + SIDE / 2 y = MARGIN + i * SIDE + SIDE / 2 original = self.game.puzzle[i][j] color = "black" if answer == original else "slate gray" 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 oval 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 __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.puzzle[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.answer[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 __clear_answers(self): self.game.set_answer_to_puzzle() self.canvas.delete("victory") self.__draw_puzzle()
class main(Frame): def __init__(self, master): root_frame = Frame(master) root_frame.pack() menubar = Menu(master) menufile = Menu(menubar, tearoff=0) menufile.add_command(label="Open") menufile.add_command(label="Save") menubar.add_cascade(label="File", menu=menufile) master.config(menu=menubar) right_frame = Frame(root_frame, bg="white") right_frame.pack(side=RIGHT) self.button = Button(right_frame, text="quit", fg="red", command=root_frame.quit) self.button.pack(side=TOP) MODES = [("3D", "rectangle"), ("2D", "line")] self.mode = StringVar() self.mode.set("line") for text, mode in MODES: b = Radiobutton(right_frame, text=text, variable=self.mode, value=mode) b.pack(anchor=W) self.camera_canvas = Canvas(right_frame, bg="red") self.camera_canvas.bind("<ButtonPress-1>", self.pressed) self.camera_canvas.bind("<B1-Motion>", self.moved) self.camera_canvas.bind("<ButtonRelease-1>", self.released) self.camera_canvas.pack(side=BOTTOM) self.plot_canvas = Canvas(root_frame, width=100, bg="blue") self.plot_canvas.pack(side=LEFT) self.tomogram_canvas = Canvas(root_frame, bg="black") self.tomogram_canvas.pack(side=LEFT) def pressed(self, event): self.start_pos = (event.x, event.y) def moved(self, event): self.camera_canvas.delete(tk.ALL) coordinates = self.start_pos + (event.x, event.y) selector = { "line": self.camera_canvas.create_line, "rectangle": self.camera_canvas.create_rectangle }[self.mode.get()] selector(*coordinates) def released(self, event): pass def plot(points): ax = self.plot_canvas p2 = points.roll(1) a = zip(points, p2) a.pop() lines = [(p[0], y1, p[1], y1 + 1) for p in a] create_line = lambda coordinate: ax.create_line(*coordinate) map(create_line, lines)
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()
global DRAGITEMX global DRAGITEMY if not DRAGITEM: return # compute how much this object has moved delta_x = event.x - DRAGITEMX delta_y = event.y - DRAGITEMY # move the object the appropriate amount canvas.move(DRAGITEM, delta_x, delta_y) # record the new position DRAGITEMX = event.x DRAGITEMY = event.y #Binds the dragging events to the left click button canvas.bind("<ButtonPress-1>", OnButtonPress) canvas.bind("<ButtonRelease-1>", OnButtonRelease) canvas.bind("<B1-Motion>", OnMotion) #Function to determine if a node is being dragged def isDragged(node): return DRAGITEM and DRAGITEM == node._index def open_file(fName): """Returns the open file or None on IOError""" try: return open(fName) except IOError: return None
from tkinter import * def draw_line(event): global click_number global x1, y1 if click_number == 0: x1 = event.x y1 = event.y click_number = 0 my_window = Tk() my_canvas = Canvas(my_window, width=400, height=400, background='white') my_canvas.grid(row=0, column=0) my_canvas.bind('<Button-1>', draw_line) click_number = 0 my_window.mainloop() #Final Flood fill from tkinter import * def draw_line(event): global click_number global x1, y1 if click_number == 0: x1 = event.x y1 = event.y click_number = 0
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
def paintTest(): global canvas master = Tk() canvas_width = win_max_x canvas_height = win_max_y canvas = Canvas(master, width=win_max_x, height=win_max_y) canvas.pack() y = int(win_max_y / 2) #w.create_line(0, y, win_max_x, y, fill="#476042") img = PhotoImage(master=master, width=win_max_x, height=win_max_y) #img = w.create_image(0,0, state="normal") canvas.bind("<Button-1>", click) mainloop() return for x in range(0, win_max_x): for y in range(0, win_max_y): color = 128 + int(64 * sin(x * y / 16.0)) drawColor = color_rgb(255, color, color) img.put(drawColor, (x, y)) w.create_image((win_max_x / 2, win_max_y / 2), image=img, state="normal") #w.create_image((win_max_x/2, win_max_y/2), image=img, state="normal") mainloop() return WIDTH, HEIGHT = 640, 480 window = Tk() canvas = Canvas(window, width=WIDTH, height=HEIGHT, bg="#000000") canvas.pack() img = PhotoImage(width=WIDTH, height=HEIGHT) canvas.add #canvas.create_image((WIDTH/2, HEIGHT/2), image=img, state="normal") for x in range(4 * WIDTH): y = int(HEIGHT / 2 + HEIGHT / 4 * sin(x / 80.0)) img.put("#ffffff", (x // 4, y)) #win.getMouse() return img = Image.New('RGB', (255, 255), "black") # create a new black image pixels = img.load() # create the pixel map for i in range(img.size[0]): # for every pixel: for j in range(img.size[1]): pixels[i, j] = (i, j, 100) # set the colour accordingly img.show() return master = Tk() canvas = Canvas(master, width=win_max_x, height=win_max_y) canvas.pack() #img = PhotoImage(file="myimage.jpg") #canvas.create_image(20,20, anchor=NW, image=img) return #pixels = " ".join('#%02x%02x%02x') img = Image.new('RGB', (255, 255), "black") # create a new black image pixels = img.load() # create the pixel map for i in range(img.size[0]): # for every pixel: for j in range(img.size[1]): pixels[i, j] = (i, j, 100) # set the colour accordingly #img.Show(win) myImage = graphics.Image(pixels) myImage.draw(window)
class Container(Frame): def __init__(self, parent, width, height): Frame.__init__(self, parent, background="#22aaff") self.parent = parent self.initUI(width, height) def initUI(self, width, height): self.inMenu = True self.width = width self.height = height self.parent.title("Stripes") self.style = Style() self.style.theme_use('default') #clam, default, alt, classic self.pack(fill=BOTH, expand=1) self.canvas = Canvas(self, width=width, height=height-30, background='#335533') def resize(event): self.width = event.width self.height = event.height if self.inMenu: pass else: self.draw() self.bind('<Configure>', resize) self.canvas.bind('<B1-Motion>', lambda(e): motion(e, self, self.draw)) self.canvas.bind('<ButtonRelease-1>', lambda(e): release(e, self, self.draw)) self.canvas.bind('<MouseWheel>', lambda(e): zoom(e, self, self.draw)) def initializeLevel(levelNum): self.currentLevel = levelNum self.inMenu = False self.canvas.delete('all') self.camera = Camera(200, pi / 40) self.cells = CellGroup('cube', '3', 4, self) file = open('levels.txt', 'r') colors = eval(file.readline()) file.close() self.routes = RouteGroup('cube', '3', 4, levelNum, self.cells, self, colors) self.activeIndex = 0 self.draw() hideIdcs(self, self.draw) numLevels = 10 def save(toMenu): lines = [] file = open('levels.txt', 'r+') for i in range(numLevels+2): lines.append(file.readline()) levelInfo = eval(lines[self.currentLevel+1]) percent = self.cells.percent(self.routes.routes) complete = self.routes.complete() if percent < levelInfo[2]: percent = levelInfo[2] if levelInfo[1] == True: complete = True nodes = levelInfo[0] lines[self.currentLevel+1] = '(' + str(nodes) + ',' + str(complete) + ',' + str(percent) + ')\n' file.seek(0) for line in lines: file.write(line) file.write('\n' + lines[len(lines)-1]) file.close() if toMenu: showLevelSelection(self, initializeLevel, numLevels) frame = Frame(self, width=width, height=30,background='#999999') menuButton = Button(self, text="Level Select", command=lambda: save(True)) menuButton.pack(in_=frame, side=LEFT, anchor=W, ipadx=6, padx=6) closeButton = Button(self, text="Close", command=self.quit) closeButton.pack(in_=frame, side=LEFT, anchor=E, padx=6) showButton = Button(self, text='Show #s', command=lambda: showIdcs(self, self.draw)) showButton.pack(in_=frame, side=LEFT, anchor=E, padx=6) hideButton = Button(self, text='Hide #s', command=lambda: hideIdcs(self, self.draw)) hideButton.pack(in_=frame, side=LEFT, anchor=E, padx=6) frame.pack(anchor=W, fill=BOTH, expand=1) self.canvas.pack(fill=BOTH, expand=1) showLevelSelection(self, initializeLevel, numLevels) def draw(self): drawCells(self) drawRoutes(self)
global DRAGITEM global DRAGITEMX global DRAGITEMY if not DRAGITEM: return # compute how much this object has moved delta_x = event.x - DRAGITEMX delta_y = event.y - DRAGITEMY # move the object the appropriate amount canvas.move(DRAGITEM, delta_x, delta_y) # record the new position DRAGITEMX = event.x DRAGITEMY = event.y #Binds the dragging events to the left click button canvas.bind("<ButtonPress-1>", OnButtonPress) canvas.bind("<ButtonRelease-1>", OnButtonRelease) canvas.bind("<B1-Motion>", OnMotion) #Function to determine if a node is being dragged def isDragged(node): return DRAGITEM and DRAGITEM == node._index def open_file(fName): """Returns the open file or None on IOError""" try: return open(fName) except IOError:
global scaling_factor if event.char == '>': scaling_factor = scaling_factor + 0.1 resize() elif event.char == '<': scaling_factor = scaling_factor - 0.1 resize() elif event.char == "<Right>": x = x + 5 print x (x, y) = canvas.coords(zoeid) canvas.bind("<Right>", lambda event: canvas.move(zoeid, 5, 0)) canvas.bind("<Left>", lambda event: canvas.move(zoeid, -5, 0)) canvas.bind("<Up>", lambda event: canvas.move(zoeid, 0, -5)) canvas.bind("<Down>", lambda event: canvas.move(zoeid, 0, 5)) canvas.focus_set() canvas.bind("<Key>", key) scaling_factor = 1.0 def resize(): global canvas, zoeid, photo1, Zoe, scaling_factor, coorx, coory, x, y
""" Construye un interfaz de usuario que permita dibujar lineas rectas en una ventana. """ from Tkinter import Tk, Canvas start = None def onclick_handler(event): global start start = (event.x, event.y) def onrelease_handler(event): global start if start is not None: x = start[0] y = start[1] event.widget.create_line(x, y, event.x, event.y) start = None master = Tk() canvas = Canvas(master, width=200, height=200) canvas.bind("<Button-1>", onclick_handler) canvas.bind("<ButtonRelease-1>", onrelease_handler) canvas.pack() master.mainloop()
# It is a dummy element, it's kind of out of the box everywhere gen_fict_square = gen_canvas.create_rectangle(0, 0, 0, 0, state=HIDDEN, tags=('hid', '0')) gen_cell_matrix.append(gen_fict_square) # Add glider gen_canvas.itemconfig(gen_cell_matrix[gen_addr(3, 3)], state=NORMAL, tags='vis') gen_canvas.itemconfig(gen_cell_matrix[gen_addr(3, 4)], state=NORMAL, tags='vis') gen_canvas.itemconfig(gen_cell_matrix[gen_addr(3, 5)], state=NORMAL, tags='vis') gen_canvas.itemconfig(gen_cell_matrix[gen_addr(4, 2)], state=NORMAL, tags='vis') gen_canvas.itemconfig(gen_cell_matrix[gen_addr(4, 3)], state=NORMAL, tags='vis') gen_canvas.itemconfig(gen_cell_matrix[gen_addr(4, 4)], state=NORMAL, tags='vis') # Add board. It is diferent representation the game fild board = set() # Setup frame of window and buttons gen_frame = Frame(gen_root) gen_button1 = Button(gen_frame, text='Generate', command=gen_generate) gen_button2 = Button(gen_frame, text='Clear', command=gen_clear) gen_button1.pack(side='left') gen_button2.pack(side='right') gen_frame.pack(side='bottom') # Event binding gen_canvas.bind('<B1-Motion>', gen_draw) gen_canvas.bind('<ButtonPress>', gen_draw) # Infiniteloop gen_root.mainloop()
class Simulator: robot = None def __init__(self, world, width=1000, height=800): self.width = width self.height = height self.master = Tk() self.canvas = Canvas(self.master, width=width, height=height) canvas = self.canvas canvas.pack() self.world = world world.display(canvas) self.localizer = ParticleFilter(N=3000, width=width, height=height) localizer = self.localizer localizer.display(canvas) def interactive(self): """Start interactive mode (doesn't return)""" print "Click anywhere on the canvas to place the robot" def callback(event): print "@", event.x, ",", event.y self.place_robot(event.x, event.y) self.canvas.bind("<Button-1>", callback) mainloop() def explore(self, x, y, moves, delay=0.5): self.place_robot(x, y) for (x, y) in moves: self.move_robot(x, y) time.sleep(delay) def measurement_probabilty(self, particle, Z): loss = self.world.binary_loss(particle, Z) if loss: particle.color = "blue" else: particle.color = "gray" return loss def move_robot(self, rotation, distance): robot = self.robot canvas = self.canvas localizer = self.localizer if not robot: raise ValueError( "Need to place robot in simulator before moving it") original_x = robot.x original_y = robot.y robot.move(rotation, distance) if robot.color and not robot.color == "None": canvas.create_line(original_x, original_y, robot.x, robot.y) Z = self.world.surface(robot.x, robot.y) self.localizer.erase(canvas) localizer.update( rotation, distance, lambda particle: self.measurement_probabilty(particle, Z)) localizer.display(canvas) robot.display(canvas) self.master.update() print "Sense:", Z def place_robot(self, x=None, y=None, bearing=None, color="green"): """Move the robot to the given position on the canvas""" if not self.robot: land = self.world.terrain[0] if not x: x = random.randint(land[0], land[2]) if not y: y = random.randint(land[1], land[3]) self.robot = Robot(x, y) self.robot.display_noise = 0.0 self.robot.color = color self.robot.size = 5 robot = self.robot if not bearing: bearing = atan2((y - robot.y), (x - robot.x)) rotation = bearing - robot.orientation distance = sqrt((robot.x - x)**2 + (robot.y - y)**2) self.move_robot(rotation, distance) return self.robot
class text_canvas(Frame): def __init__(self, parent, font_size, input_handler, filename): Frame.__init__(self, parent) self.parent = parent self.text_font = tkFont.Font(family='Monaco', size=font_size, weight='bold') self.filename = filename self.cheight, self.cwidth, self.line_num_spacing = font_size, self.text_font.measure('c'), 50 self.line_height = ((self.winfo_screenheight() - self.cheight)/(self.cheight + 2) - 4) self.init_UI(input_handler) def init_UI(self, input_handler): self.parent.title('') self.pack(fill=BOTH, expand=1) self.init_canvas(input_handler) def get_dimensions(self): return { 'cheight': self.cheight, 'cwidth': self.cwidth, 'line_num_spacing':self.line_num_spacing, 'line_height': self.line_height, 'screen_width': self.winfo_screenwidth(), 'screen_height': self.winfo_screenheight() } def init_canvas(self, input_handler): self.canvas = Canvas(self, highlightthickness=0, width=self.winfo_screenwidth(), height=self.winfo_screenheight(), bg=options['background_color']) self.canvas.pack() self.canvas.focus_set() self.bind_events(input_handler) def clear_all(self): self.canvas.delete('all') def get_line_height(self): return self.line_height def get_grid_y(self, y): return self.cheight * y + (y * 2) def write_line_grid(self, y, line): for token in line: self.write_text_grid(token[0], y, token[1], token[2]) # write line of text at given grid co-ordinates def write_text_grid(self, x, y, text, color=options['text_color']): x_val = self.cwidth * x + self.line_num_spacing # 2 pixel spacing between each line y_val = self.cheight * y + (y * 2) self.canvas.create_text(x_val, y_val, anchor='nw', text=text, font=self.text_font, fill=color) def write_status_line(self, text, textcolor=options['status_text_color'], backgroundcolor=options['status_background_color']): y = self.line_height + 1 self.canvas.create_rectangle(0, self.cheight * y + (y * 2), self.winfo_screenwidth(), self.cheight * y + (y * 2) + self.cheight + 4, fill=backgroundcolor, outline=backgroundcolor) self.write_text_grid(0, self.line_height + 1, text, textcolor) def draw_highlight_grid(self, y, x1, x2, highlightcolor=options['text_highlight_color']): y_val = self.cheight * y + (y * 2) x1_val = self.cwidth * x1 + self.line_num_spacing x2_val = self.cwidth * x2 + self.line_num_spacing self.canvas.create_rectangle(x1_val, y_val, x2_val, y_val + self.cheight + 4, fill=highlightcolor, outline=highlightcolor) def draw_line_numbers(self, start, highlightcolor=options['line_num_highlight_color'], textcolor=options['line_num_text_color']): self.canvas.create_rectangle(0, 0, self.line_num_spacing / 2, self.winfo_screenheight(), fill=highlightcolor, outline=highlightcolor) for i in range(self.line_height + 1): self.canvas.create_text(0, self.cheight * i + (i * 2), anchor='nw', text=str(start + i), font=self.text_font, fill=textcolor) def draw_cursor(self, x, y, highlightcolor=options['cursor_highlight_color'], cursorcolor=options['cursor_color']): x_val = self.cwidth * x + self.line_num_spacing y_val = self.cheight * y + (y * 2) self.canvas.create_rectangle(0, y_val, self.winfo_screenwidth(), y_val + self.cheight + 4, fill=highlightcolor, outline=highlightcolor) self.canvas.create_rectangle(x_val, 0, x_val + self.cwidth, self.winfo_screenheight(), fill=highlightcolor, outline=highlightcolor) self.canvas.create_rectangle(x_val, y_val, x_val + self.cwidth, y_val + self.cheight + 4, fill=cursorcolor, outline=cursorcolor) def draw_rectangle_absolute(self, x1, y1, x2, y2, color): self.canvas.create_rectangle(x1, y1, x2, y2, fill=color, outline=color) def bind_events(self, input_handler): # TODO: this should be cleaned up ideally into a separate handler list input_handler.set_GUI_reference(self) self.canvas.bind('<Key>', input_handler.key) self.canvas.bind_all('<Escape>', input_handler.escape) self.canvas.bind_all('<Control-a>', input_handler.control_a) self.canvas.bind_all('<Control-b>', input_handler.control_b) self.canvas.bind_all('<Control-c>', input_handler.control_c) self.canvas.bind_all('<Control-d>', input_handler.control_d) self.canvas.bind_all('<Control-e>', input_handler.control_e) self.canvas.bind_all('<Control-f>', input_handler.control_f) self.canvas.bind_all('<Control-g>', input_handler.control_g) self.canvas.bind_all('<Control-h>', input_handler.control_h) self.canvas.bind_all('<Control-i>', input_handler.control_i) self.canvas.bind_all('<Control-j>', input_handler.control_j) self.canvas.bind_all('<Control-k>', input_handler.control_k) self.canvas.bind_all('<Control-l>', input_handler.control_l) self.canvas.bind_all('<Control-m>', input_handler.control_m) self.canvas.bind_all('<Control-n>', input_handler.control_n) self.canvas.bind_all('<Control-o>', input_handler.control_o) self.canvas.bind_all('<Control-p>', input_handler.control_p) self.canvas.bind_all('<Control-q>', input_handler.control_q) self.canvas.bind_all('<Control-r>', input_handler.control_r) self.canvas.bind_all('<Control-s>', input_handler.control_s) self.canvas.bind_all('<Control-t>', input_handler.control_t) self.canvas.bind_all('<Control-u>', input_handler.control_u) self.canvas.bind_all('<Control-v>', input_handler.control_v) self.canvas.bind_all('<Control-w>', input_handler.control_w) self.canvas.bind_all('<Control-x>', input_handler.control_x) self.canvas.bind_all('<Control-y>', input_handler.control_y) self.canvas.bind_all('<Control-z>', input_handler.control_z) self.canvas.bind_all("<MouseWheel>", input_handler.mouse_scroll) self.canvas.bind_all('<Control-braceright>', input_handler.control_braceright) self.canvas.bind_all('<Control-braceleft>', input_handler.control_braceleft)
class ImageViewer(Frame, object): class _Panner(object): def __init__(self): self.viewers = [] self._factor = 1 self._drags = [] self._cdrag = None def add(self, val): self.viewers.append(val) for mark, end in self._drags: val.canvas.scan_mark(*mark) val.canvas.scan_dragto(*end, gain=1) if self._cdrag: val.canvas.scan_mark(*self._cdrag[0]) val.canvas.scan_dragto(*self._cdrag[1], gain=1) def move_mark(self, x, y): if self._cdrag: self._drags.append(self._cdrag) self._cdrag = [(x, y), (x, y)] for viewer in self.viewers: viewer.canvas.scan_mark(x, y) def move_actual(self, x, y): self._cdrag[1] = (x, y) for viewer in self.viewers: viewer.canvas.scan_dragto(x, y, gain=1) def update(self): for viewer in self.viewers: viewer._update() def __init__(self, master, panner=None): super(ImageViewer, self).__init__(master) self._image = None self._view = None self._view_id = None self.canvas = Canvas(self, background="#000") self.canvas.pack(fill='both', expand=1) self.canvas.bind("<MouseWheel>", self.zoom) self.canvas.bind("<ButtonPress-1>", self.scroll_start) self.canvas.bind("<B1-Motion>", self.scroll_move) # self.canvas.bind("<Enter>", self.focus_widget) # self.canvas.bind("<Leave>", self.unfocus_widget) self.popup_menu = PopupMenu(self.canvas) for val in (10, 25, 50, 75, 100, 150, 200, 250, 300, 500): self.popup_menu.add_command(label="%d%%"%val, command=(lambda v:(lambda :self.set_factor(v/100.)))(val)) self.popup_menu.attach() self._panner = panner if panner is None: self._panner = ImageViewer._Panner() self._panner.add(self) self._focus_prev = None def destroy(self): self._panner.viewers.remove(self) super(ImageViewer, self).destroy() @property def image(self): return self._image @image.setter def image(self, value): self._image = value self.after(1, self.show) @property def factor(self): return self._panner._factor @factor.setter def factor(self, value): self._panner._factor = value self.after(1, self.show) def set_factor(self, value): self.factor = value def zoom(self, event): if event.delta < 0: if self.factor == .1: return self.factor -= .1 elif event.delta > 0: if self.factor == 5: return self.factor += .1 self.show() def scroll_start(self, event): self._panner.move_mark(event.x, event.y) def scroll_move(self, event): self._panner.move_actual(event.x, event.y) def focus_widget(self, event): self._focus_prev = self.canvas.focus_get() self.focus_set() def unfocus_widget(self, event): self._focus_prev.focus_set() def show(self): self._panner.update() def _update(self): if self._image is None: return if self._view_id is not None: self.canvas.delete(self._view_id) x, y = self.image.size x, y = int(round(x*self.factor)), int(round(y*self.factor)) self._view = ImageTk.PhotoImage(self.image.resize((x, y))) self._view_id = self.canvas.create_image(0, 0, image=self._view, anchor="nw") self.canvas.configure(scrollregsion=self.canvas.bbox("ALL"))
bg="White", aspect=300) #Information message def on_enterinvmass(event): """shows an explanation if cursor placed over question mark""" infoinvmass.grid(row=0, rowspan=8) def on_leaveinvmass(event): """hides explanation if cursor not placed on question mark""" infoinvmass.grid_forget() #Def and bind two functions for when cursor is over question mark or leaves qinvmass.bind("<Enter>", on_enterinvmass) qinvmass.bind("<Leave>", on_leaveinvmass) #Question mark to be next to "invariant mass of pair" option qbinvmass = Canvas(OptionsLep, width=16, height=16) qbinvmass.create_image(8, 8, image=questionmark) infobinvmass = Message(OptionsLep, text="""Finds the lepton pair with the closest invariant mass subject to the other conditions.""", bg="White", aspect=300) #Information message
class SurfaceManipulator(Frame): r""" A translation surface editor in tk. """ # STATIC METHODS AND OBJECTS current = None # boolean variable to remember if the hook was run! _clear_hook_was_run = 0 @staticmethod def launch(geometry="800x700+10+10"): r"""Prefered way to gain access to a SurfaceManipulator window.""" if SurfaceManipulator.current is None: SurfaceManipulator._clear_hook() root = Tk() root.geometry(geometry) SurfaceManipulator.current = SurfaceManipulator(root) return SurfaceManipulator.current @staticmethod def _window_destroyed(surface_manipulator): if SurfaceManipulator.current is surface_manipulator: SurfaceManipulator.current = None @staticmethod def _clear_hook(): if not SurfaceManipulator._clear_hook_was_run: # Hack due to Nathan Dunfield (http://trac.sagemath.org/ticket/15152) import IPython.lib.inputhook as ih ih.clear_inputhook() SurfaceManipulator._clear_hook_was_run = 1 # NORMAL METHODS def __init__(self, parent, surface=None, surfaces=[]): r""" INPUT: - ``surfaces`` -- a list of surfaces that the editor may modify - ``surface`` -- surface selected by default - ``parent`` -- parent Tk window """ Frame.__init__(self, parent) self._parent = parent self.pack(fill="both", expand=1) # Run something when closing self._parent.wm_protocol("WM_DELETE_WINDOW", self.exit) # Surface currently being manipulated self._surface = None # List of surfaces in editor self._surfaces = [] # More variables to initialize self._currentActor = None # Initialization of GUI self._init_menu() self._init_gui() # Setup surface list for s in surfaces: self.add_surface(s) # Setup initial surface if surface is not None: self.add_surface(surface) self.set_surface(surface) def __repr__(self): return "Surface manipulator" def add_mega_wollmilchsau(self): from geometry.mega_wollmilchsau import MegaWollmilchsau s = MegaWollmilchsau() sm, sb = s.get_bundle() self.set_surface(sb) def add_octagon(self): from geometry.similarity_surface_generators import TranslationSurfaceGenerators ss = TranslationSurfaceGenerators.regular_octagon() ss.edit() def _init_menu(self): self._menubar = Menu(self._parent) menubar = self._menubar self._parent.config(menu=menubar) #new_menu = Menu(menubar, tearoff=0) #new_menu.add_command(label="Billiard Table", command=self.on_new_similarity_surface) file_menu = Menu(menubar, tearoff=0) #file_menu.add_cascade(label="New", menu=new_menu) file_menu.add_command(label="Octagon", command=self.add_octagon) file_menu.add_command(label="MegaWollmilchsau", command=self.add_mega_wollmilchsau) file_menu.add_separator() file_menu.add_command(label="About", command=self.on_about) file_menu.add_command(label="Export PostScript", command=self.on_export) file_menu.add_command(label="Exit", command=self.exit, accelerator="Alt+F4") menubar.add_cascade(label="File", underline=0, menu=file_menu) self._surface_menu = Menu(menubar, tearoff=0) self._selected_surface = IntVar() self._selected_surface.set(-1) menubar.add_cascade(label="Surface", underline=0, menu=self._surface_menu) self._surface_menu.add_radiobutton(label="None", command=self.menu_select_surface, variable=self._selected_surface, value=-1) def _init_gui(self): self._parent.title("FlatSurf Editor") self._canvas = Canvas(self, bg="#444", width=300, height=200) self._canvas.pack(fill="both", expand=1) self.bottom_text = Label(self, text="Welcome to FlatSurf.", anchor="w") self.bottom_text.pack(fill="x", expand=0) self.set_actor(None) def add_surface(self, newsurface): r""" Add a surface to the display list for the window. Returns the index of the new surface in the surface list. """ if (newsurface == None): return -1 i = 0 for s in self._surfaces: if (s == newsurface): return i i = i + 1 self._surfaces.append(newsurface) newsurface.zoom_fit_nice_boundary() self._reset_surface_menu() return len(self._surfaces) - 1 def exit(self): SurfaceManipulator._window_destroyed(self) self._parent.destroy() def find_bundle(self, surface): for surface_bundle in self._surfaces: if surface is surface_bundle.get_surface(): return surface_bundle return None def get_bundle(self): return self._surface def get_bundles(self): return self._surfaces def get_canvas(self): return self._canvas def get_center(self): r""" Return the center of the canvas as a pair of integers. """ return (self.get_width() / 2, self.get_height() / 2) def get_height(self): r""" Return the height of the canvas (an integer). """ return self.get_canvas().winfo_height() def get_parent(self): return self._parent def get_surface_bundle(self): r""" Get the current surface bundle, or None if there is none. """ return self._surface def get_width(self): r""" Return the width of the canvas (an integer). """ return self.get_canvas().winfo_width() def menu_select_surface(self): r""" Called when a surface is selected from a menu. """ i = self._selected_surface.get() if i == -1: self.set_surface(None) else: self.set_surface(self._surfaces[i]) def on_about(self): self.set_text("Written by Vincent Delecroix and Pat Hooper.") def on_delete_junk(self): self._canvas.delete("junk") def on_export(self): r""" Export image as postscript file. """ myFormats = [('PostScript', '*.ps')] fileName = tkFileDialog.asksaveasfilename(parent=self, filetypes=myFormats, title="Save image as...") if len(fileName) > 0: self._canvas.update() self._canvas.postscript(file=fileName) self.set_text("Wrote image to " + fileName) # def on_new_similarity_surface(self): # s = CreateSimilaritySurfaceBundle(len(self._surfaces),self) # if s is not None: # i = self.set_surface(s) # self.set_text("Created new surface `"+self._surfaces[i].get_name()+"'.") def _on_no_surface(self): self._canvas.delete("all") def _on_zoom(self): self.set_actor(ZoomActor(self)) def _on_zoom_box(self): self.set_actor(ZoomBoxActor(self)) def _on_redraw_all(self): if self._surface is not None: self._surface.redraw_all() def _on_recenter(self): self.set_actor(RecenterActor(self)) def _reset_menus(self): r""" Reset all menus except the file and surface menu """ # The following loop removes all but the first two menus (File and Surface). num = len(self._menubar.children) for i in range(num, 2, -1): self._menubar.delete(i) if self._surface != None: self._surface.make_menus(self._menubar) def _reset_surface_menu(self): r""" Reset the surface menu. """ ### This is a hack to get the number of items in the menu: num = self._surface_menu.index(100) + 1 # First we remove everything but the first entry ("None") for i in range(num - 1, 0, -1): #print("removing a child2: "+str(i)+" of "+str(num)) self._surface_menu.delete(i) # Add an entry for every surface in the list. for i in range(len(self._surfaces)): surface = self._surfaces[i] self._surface_menu.add_radiobutton( label=surface.get_name(), command=self.menu_select_surface, variable=self._selected_surface, value=i) def set_text(self, text): self.bottom_text["text"] = text def set_actor(self, actor): r""" Set the current mode of user interaction. """ if (actor != self._currentActor): if self._currentActor != None: self._currentActor.on_deactivate() if (actor == None): self.set_text("Nothing going on.") # Event bindings self._canvas.unbind('<Button-1>') self._canvas.unbind('<Button-2>') self._canvas.unbind('<Button-3>') self._canvas.unbind('<Double-Button-1>') self._canvas.unbind('<Shift-Button-1>') self._canvas.unbind('<Motion>') self.unbind('<FocusIn>') self.unbind('<FocusOut>') #self._canvas.unbind('<ButtonPress-1>') self._canvas.unbind('<ButtonRelease-1>') self._canvas.unbind('<B1-Motion>') self._parent.unbind('<Key>') self._parent.unbind('<KeyRelease>') else: # Event bindings self._canvas.bind('<Button-1>', actor.single_left_click) self._canvas.bind('<Double-Button-1>', actor.double_left_click) self._canvas.bind('<Triple-Button-1>', actor.double_left_click) self._canvas.bind('<Button-2>', actor.single_middle_click) self._canvas.bind('<Double-Button-2>', actor.double_middle_click) self._canvas.bind('<Triple-Button-2>', actor.double_middle_click) self._canvas.bind('<Button-3>', actor.single_right_click) self._canvas.bind('<Double-Button-3>', actor.double_right_click) self._canvas.bind('<Triple-Button-3>', actor.double_right_click) self._canvas.bind('<Shift-Button-1>', actor.shift_click) self._canvas.bind('<Motion>', actor.mouse_moved) #self._canvas.bind('<ButtonPress-1>', actor.left_mouse_pressed) self._canvas.bind('<ButtonRelease-1>', actor.left_mouse_released) self._canvas.bind('<B1-Motion>', actor.left_dragged) self.bind('<FocusIn>', actor.focus_in) self.bind('<FocusOut>', actor.focus_out) self._parent.bind('<Key>', actor.key_press) self._parent.bind('<KeyRelease>', actor.key_release) self._currentActor = actor self._currentActor.on_activate() def set_surface(self, surface_bundle): r""" Set the current surface to the one given by surface_bundle """ i = self.add_surface(surface_bundle) if surface_bundle != self._surface: self._canvas.delete("all") self._surface = surface_bundle self._surface_menu.invoke(i + 1) if i >= 0: self.set_text("Switched to `" + self._surface.get_name() + "'.") self._parent.title(self._surface.get_name()) self._reset_menus() # stop the actor (was a bug). self.set_actor(None) if isinstance(self._surface, EditorRenderer): self._surface.initial_render() else: self.set_text("No surface selected.") self._parent.title("FlatSurf Editor") self._reset_menus() self.set_actor(None) return i def surface_renamed(self): if self._surface is not None: self._parent.title(self._surface.get_name()) self._reset_surface_menu()
return length def callback(event, reset): #note, when sending to database, add 400 to x and 300 to y global lines global lineNumber global toSum global canvas if reset == 1: #if we release the button for i in range(len(lineNumber)): #delete the lines drawn canvas.delete(lineNumber[i]) if len(lines) > 1: # if it was dragged value = ((400+lines[0][0], 300+lines[0][1]), (400+lines[-1][0], 300+lines[-1][1]), getReturn(toSum)) else: #if it was clicked value = ((400+event.x, 300+event.y), (0,0), 0) lineNumber = [] #empty our lists lines = [] toSum = [] print(value) #return the start, end and distance travelled return if (len(lines)) == 0: #if we just started drawing lines.append((event.x, event.y)) else: #we're in the middle of drawing toSum.append(((lines[-1][0], lines[-1][1]), (event.x, event.y), dist((lines[-1][0], lines[-1][1]), (event.x, event.y)))) lineNumber.append(canvas.create_line((lines[-1][0], lines[-1][1]), (event.x, event.y), fill="red")) lines.append((event.x, event.y)) canvas.bind("<B1-Motion>",func = lambda event: callback(event, 0), add = "+") canvas.bind("<ButtonRelease-1>", func = lambda event: callback(event, 1)) root.mainloop()
class GridObj(Frame): """The GridObj class is a UI element for a cell in a grid of carts.""" _cart = None _key = None _is_playing = False _rect = None _title = None _issuer = None _length = None _on_left_click = None _on_right_click = None _on_cart_end = None def __init__(self, parent, key, on_left_click, on_right_click, on_cart_end): """Construct a grid object. :param parent :param on_left_click: callback for left click :param on_right_click: callback for right click :param on_cart_end: callback for when a cart ends """ Frame.__init__(self, parent.master, bd=1, relief=Tkinter.SUNKEN, bg=COLOR_DEFAULT, width=CART_WIDTH, height=CART_HEIGHT) self._key = key self._on_left_click = on_left_click self._on_right_click = on_right_click self._on_cart_end = on_cart_end self._rect = Canvas(self, width=CART_WIDTH, height=CART_HEIGHT, bg=COLOR_DEFAULT) self._title = self._rect.create_text(5, 5, width=CART_WIDTH, anchor=Tkinter.NW, font=FONT, fill=COLOR_TITLE, text="") self._issuer = self._rect.create_text(CART_WIDTH / 2, 25, width=CART_WIDTH, anchor=Tkinter.N, font=FONT, fill=COLOR_ISSUER, text="") self._length = self._rect.create_text(CART_WIDTH / 2, CART_HEIGHT - 15, anchor=Tkinter.S, font=FONT, fill=COLOR_LENGTH, text="") self._rect.bind("<ButtonPress-1>", self._left_click) self._rect.bind("<Button-2>", self._right_click) self._rect.bind("<Button-3>", self._right_click) self._rect.pack() def has_cart(self): """Get whether the grid object has a cart.""" return self._cart is not None def get_cart(self): """Get the cart of the grid object.""" return self._cart def set_cart(self, cart): """Set a cart for the grid object. :param cart """ self._cart = cart length = self._cart.get_meter_data()[1] / 1000 self._rect.itemconfigure(self._title, text=self._cart.title) self._rect.itemconfigure(self._issuer, text=(self._cart.issuer + " " + self._cart.cart_id)) self._rect.itemconfigure(self._length, text=get_fmt_time(length)) self._rect["bg"] = COLOR_TYPES_NEW[self._cart.cart_type] def remove_cart(self): """Remove a cart from the grid object.""" self._cart = None self._rect.itemconfigure(self._title, text="") self._rect.itemconfigure(self._issuer, text="") self._rect.itemconfigure(self._length, text="") self._rect["bg"] = COLOR_DEFAULT def is_playing(self): """Get whether the cart is playing.""" return self._is_playing def start(self): """Start the grid object.""" self._is_playing = True self._rect["bg"] = COLOR_PLAYING self._cart.start(self._cart_end) database.log_cart(self._cart.cart_id) def stop(self): """Stop the grid object.""" self._is_playing = False self._rect["bg"] = COLOR_TYPES_PLAYED[self._cart.cart_type] self._cart.stop() def _left_click(self, *args): """Respond to a left click.""" self._on_left_click(self, self._key) def _right_click(self, *args): """Respond to a right click.""" self._on_right_click(self) def _cart_end(self): """Respond to the end of the cart.""" self._on_cart_end(self._key)
cell_size + cell_size * i - 2, fill=fill_color) canvas.itemconfig(square, state=HIDDEN, tags=('hid', '0')) cell_matrix.append(square) fict_square = canvas.create_rectangle(0, 0, 0, 0, state=HIDDEN, tags=('hid', '0')) cell_matrix.append(fict_square) canvas.itemconfig(cell_matrix[addr(8, 8)], state=NORMAL, tags='vis') canvas.itemconfig(cell_matrix[addr(10, 9)], state=NORMAL, tags='vis') canvas.itemconfig(cell_matrix[addr(9, 9)], state=NORMAL, tags='vis') canvas.itemconfig(cell_matrix[addr(9, 8)], state=NORMAL, tags='vis') canvas.itemconfig(cell_matrix[addr(9, 7)], state=NORMAL, tags='vis') canvas.itemconfig(cell_matrix[addr(10, 7)], state=NORMAL, tags='vis') frame = Frame(root) btn1 = Button(frame, text='Eval', command=step) btn2 = Button(frame, text='Clear', command=clear) btn1.pack(side='left') btn2.pack(side='right') frame.pack(side='bottom') canvas.bind('<B1-Motion>', draw_a) canvas.bind('<ButtonPress>', draw_a) root.mainloop()
drawOval(event) # print 'Mouse click: ' + str(event.x) + ', ' + str(event.y) def mouseMove(event): drawOval(event) # print 'Mouse move: ' + str(event.x) + ', ' + str(event.y) def drawOval(event): global mouseX, mouseY showMouse = True mouseX = event.x mouseY = event.y updateCanvas() # Mouse Events canvas.bind("<Button-1>", mouseClick) canvas.bind("<B1-Motion>", mouseMove) canvas.grid(row=0,column=0, rowspan=100) ################################ ######### Pixel Mapping ######## ################################ pixelMapping = [] ################################ ########## Board Coms ########## ################################ cmdMessage = StringVar()
class Simulator: robot = None def __init__(self, world, width=1000, height=800): self.width = width self.height = height self.master = Tk() self.canvas = Canvas(self.master, width=width, height=height) canvas = self.canvas canvas.pack() self.world = world world.display(canvas) self.localizer = ParticleFilter(N=3000, width=width, height=height) localizer = self.localizer localizer.display(canvas) def interactive(self): """Start interactive mode (doesn't return)""" print "Click anywhere on the canvas to place the robot" def callback(event): print "@", event.x, ",", event.y self.place_robot(event.x, event.y) self.canvas.bind("<Button-1>", callback) mainloop() def explore(self, x, y, moves, delay=0.5): self.place_robot(x, y) for (x, y) in moves: self.move_robot(x, y) time.sleep(delay) def measurement_probabilty(self, particle, Z): loss = self.world.binary_loss(particle, Z) if loss: particle.color = "blue" else: particle. color = "gray" return loss def move_robot(self, rotation, distance): robot = self.robot canvas = self.canvas localizer = self.localizer if not robot: raise ValueError("Need to place robot in simulator before moving it") original_x = robot.x original_y = robot.y robot.move(rotation, distance) if robot.color and not robot.color == "None": canvas.create_line(original_x, original_y, robot.x, robot.y) Z = self.world.surface(robot.x, robot.y) self.localizer.erase(canvas) localizer.update(rotation, distance, lambda particle: self.measurement_probabilty(particle, Z)) localizer.display(canvas) robot.display(canvas) self.master.update() print "Sense:", Z def place_robot(self, x=None, y=None, bearing=None, color="green"): """Move the robot to the given position on the canvas""" if not self.robot: land = self.world.terrain[0] if not x: x = random.randint(land[0], land[2]) if not y: y = random.randint(land[1], land[3]) self.robot = Robot(x, y) self.robot.display_noise = 0.0 self.robot.color = color self.robot.size = 5 robot = self.robot if not bearing: bearing = atan2((y - robot.y), (x - robot.x)) rotation = bearing - robot.orientation distance = sqrt((robot.x - x) ** 2 + (robot.y - y) ** 2) self.move_robot(rotation, distance) return self.robot
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 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 main: def __init__(self,master): self.frame = Frame(master) self.frame.pack(fill="both", expand=True) self.canvas = Canvas(self.frame, width=300, height=300) self.canvas.pack(fill="both", expand=True) self.label=Label(self.frame, text='Tic Tac Toe Game', height=6, bg='black', fg='blue') self.label.pack(fill="both", expand=True) self.frameb=Frame(self.frame) self.frameb.pack(fill="both", expand=True) self.Start1=Button(self.frameb, text='Click here to start\ndouble player', height=4, command=self.start1,bg='white', fg='purple') self.Start1.pack(fill="both", expand=True, side=RIGHT) self.Start2=Button(self.frameb, text='Click here to start\nsingle player', height=4, command=self.start2,bg='purple', fg='white') self.Start2.pack(fill="both", expand=True, side=LEFT) self._board() def start1(self): self.canvas.delete(ALL) self.label['text']=('Tic Tac Toe Game') self.canvas.bind("<ButtonPress-1>", self.sgplayer) self._board() self.TTT=[[0,0,0],[0,0,0],[0,0,0]] self.i=0 self.j=False def start2(self): self.canvas.delete(ALL) self.label['text']=('Tic Tac Toe Game') self.canvas.bind("<ButtonPress-1>", self.dgplayer) self._board() self.TTT=[[0,0,0],[0,0,0],[0,0,0]] self.i=0 self.j=False self.trigger=False def end(self): self.canvas.unbind("<ButtonPress-1>") self.j=True def _board(self): self.canvas.create_rectangle(0,0,300,300, outline="black") self.canvas.create_rectangle(100,300,200,0, outline="black") self.canvas.create_rectangle(0,100,300,200, outline="black") def sgplayer(self,event): for k in range(0,300,100): for j in range(0,300,100): if event.x in range(k,k+100) and event.y in range(j,j+100): if self.canvas.find_enclosed(k,j,k+100,j+100)==(): if self.i%2==0: X=(2*k+100)/2 Y=(2*j+100)/2 X1=int(k/100) Y1=int(j/100) self.canvas.create_oval( X+25, Y+25, X-25, Y-25, width=4, outline="black") self.TTT[Y1][X1]+=1 self.i+=1 else: X=(2*k+100)/2 Y=(2*j+100)/2 X1=int(k/100) Y1=int(j/100) self.canvas. create_line( X+20, Y+20, X-20, Y-20, width=4, fill="black") self.canvas. create_line( X-20, Y+20, X+20, Y-20, width=4, fill="black") self.TTT[Y1][X1]+=9 self.i+=1 self.check() def dgplayer(self,event): for k in range(0,300,100): for j in range(0,300,100): if self.i%2==0: if event.x in range(k,k+100) and event.y in range(j,j+100): if self.canvas.find_enclosed(k,j,k+100,j+100)==(): X=(2*k+100)/2 Y=(2*j+100)/2 X1=int(k/100) Y1=int(j/100) self.canvas.create_oval( X+25, Y+25, X-25, Y-25, width=4, outline="black") self.TTT[Y1][X1]+=1 self.i+=1 self.check() self.trigger=False else: print(self.i) self.check() print("checked") self.AIcheck() print("AIchecked") self.trigger=False def check(self): #horizontal check for i in range(0,3): if sum(self.TTT[i])==27: self.label['text']=('2nd player wins!') self.end() if sum(self.TTT[i])==3: self.label['text']=('1st player wins!') self.end() #vertical check #the matrix below transposes self.TTT so that it could use the sum fucntion again self.ttt=[[row[i] for row in self.TTT] for i in range(3)] for i in range(0,3): if sum(self.ttt[i])==27: self.label['text']=('2nd player wins!') self.end() if sum(self.ttt[i])==3: self.label['text']=('1st player wins!') self.end() #check for diagonal wins if self.TTT[1][1]==9: if self.TTT[0][0]==self.TTT[1][1] and self.TTT[2][2]==self.TTT[1][1] : self.label['text']=('2nd player wins!') self.end() if self.TTT[0][2]==self.TTT[1][1] and self.TTT[2][0]==self.TTT[1][1] : self.label['text']=('2nd player wins!') self.end() if self.TTT[1][1]==1: if self.TTT[0][0]==self.TTT[1][1] and self.TTT[2][2]==self.TTT[1][1] : self.label['text']=('1st player wins!') self.end() if self.TTT[0][2]==self.TTT[1][1] and self.TTT[2][0]==self.TTT[1][1] : self.label['text']=('1st player wins!') self.end() #check for draws if self.j==False: a=0 for i in range(0,3): a+= sum(self.TTT[i]) if a==41: self.label['text']=("It's a pass!") self.end() def AIcheck(self): #This is built on the self.check function self.ttt=[[row[i] for row in self.TTT] for i in range(3)] #DEFENSE #this is the horizontal checklist for h in range(0,3): k=0 j=0 if sum(self.TTT[h])==2: while k <3: if k==h: while j <3: if self.trigger==False: if self.TTT[k][j]==0: self.cross(j,k) break j+=1 k+=1 #this is the vertical checklist for h in range(0,3): k=0 j=0 if sum(self.ttt[h])==2: while k <3: if k==h: while j <3: if self.trigger==False: if self.ttt[k][j]==0: self.cross(k,j) break j+=1 k+=1 #this is the diagonal checklist if self.TTT[1][1]==1: if self.TTT[0][0]==1: if self.trigger==False: if self.TTT[2][2]==0: self.cross(2,2) if self.TTT[0][2]==1: if self.trigger==False: if self.TTT[2][0]==0: self.cross(0,2) if self.TTT[2][0]==1: if self.trigger==False: if self.TTT[0][2]==0: self.cross(2,0) if self.TTT[2][2]==1: if self.trigger==False: if self.TTT[0][0]==0: self.cross(0,0) if self.TTT[1][1]==0: if self.trigger==False: self.cross(1,1) self.trigger=True else: if self.trigger==False: self.randmove() def cross(self, k, j): # k is the x coords # j is the y coords X=(200*k+100)/2 Y=(200*j+100)/2 X1=int(k) Y1=int(j) self.canvas. create_line( X+20, Y+20, X-20, Y-20, width=4, fill="black") self.canvas. create_line( X-20, Y+20, X+20, Y-20, width=4, fill="black") self.TTT[Y1][X1]+=9 self.check() self.i+=1 self.trigger=True def randmove(self): while True: k=(randint(0,2)) j=(randint(0,2)) if self.TTT[j][k]==0: X=(200*k+100)/2 Y=(200*j+100)/2 self.canvas. create_line( X+20, Y+20, X-20, Y-20, width=4, fill="black") self.canvas. create_line( X-20, Y+20, X+20, Y-20, width=4, fill="black") self.TTT[j][k]+=9 self.check() self.i+=1 self.trigger=True break else: k=(randint(0,2))*100 j=(randint(0,2))*100
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()
Label(but_frame, textvariable=var).pack() GSMTtext = StringVar() label4 = Label(but_frame, textvariable=GSMTtext) label4.pack() Label(but_frame, textvariable="").pack() button5 = Button(but_frame, text="Reset", command=clear) button5.configure(width=9, activebackground="blue", relief=RAISED) button5.pack(side=TOP) but_frame.pack(side=RIGHT, expand=0) canvas = Canvas(master, width=500, height=500, bd=2, relief=RIDGE, bg='#F6F5F1') canvas.bind("<Button-1>", addMousePoint) canvas.pack(expand=0) master.pack(expand=0) RMSTtext.set("-----") RSMTtext.set("-----") GMSTtext.set("-----") GSMTtext.set("-----") # Testing Points # addPoint(161, 88) # addPoint(103, 222) # addPoint(310, 143) # addPoint(256, 282)
canvas = Canvas(frame, width=500, height=200, bg="green") id1 = canvas.create_oval(50, 20, 70, 40, fill="white") id2 = canvas.create_rectangle(100,100,125,125, fill ="red") canvas.pack() def click(event): print "raton en", event.x, event.y colors = ["green","yellow","red", "black", "white"] canvas.itemconfigure(id2,fill=colors[random.randint(0,len(colors)-1)]) o = canvas.coords(id1) print "origin", o, type(o) r = o[0:2]+map(lambda x: x+4,o[-2:]) print "result", r, type(r) canvas.coords(id1,r[0],r[1],r[2],r[3]) canvas.bind("<Button-1>", click) def ejecucion_boton(): print "boton" canvas.move(id1,10,10) l.configure(text="pero...ha cambiado!"+str(random.random())) entrada.delete(0,END) entrada.insert(0,"hola"+str(time.gmtime()[5])) boton = Button(frame, text="texto de botón", command=ejecucion_boton) boton.pack() l = Label(frame, text="Un texto de etiqueta", font=my_font) l.pack() entrada = Entry(frame,width=25)
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 PhraseEditor(HasTraits): """A graphical editor for musical phrases.""" phrase = Instance(Phrase) """The phrase which is edited.""" selected_point = Instance(Point) """The point that is currently moved around.""" use_grid = Bool """Whether added points shall be snapped to a grid.""" grid_resolution = Range(2,64, 16) """The resolution of the grid.""" point_handle_size = Int(4) """The size of the handles used to move points around.""" def __init__(self, toplevel, phrase, **kwargs): """ Initializes a PhraseEditor. @param toplevel: the Tk Toplevel window @param phrase: the phrase to be edited """ # The Tk Toplevel object to which the editor will be attached self.toplevel = toplevel control_frame = Frame(self.toplevel) control_frame.pack(side=TOP) title_frame = Frame(control_frame, padx=8) title_frame.pack(side=LEFT) Label(title_frame, text="Title").pack(side=LEFT) self.title_entry_manager = EntryManager( title_frame, self, 'phrase.name' ) self.title_entry_manager.entry.pack(side=LEFT) grid_frame = Frame(control_frame, padx=8) grid_frame.pack(side=LEFT) self.grid_checkbutton_manager = CheckbuttonManager( grid_frame, self, 'use_grid', text="Grid" ) self.grid_checkbutton_manager.checkbutton.pack(side=LEFT) Label(grid_frame, text="Resolution").pack(side=LEFT) self.grid_resolution_spinbox_manager = SpinboxManager( grid_frame, self, 'grid_resolution', ) self.grid_resolution_spinbox_manager.spinbox.pack(side=LEFT) steps_frame = Frame(control_frame, padx=8) steps_frame.pack(side=LEFT) Label(steps_frame, text="Steps").pack(side=LEFT) self.steps_spinbox_manager = SpinboxManager( steps_frame, self, 'phrase.steps', ) self.steps_spinbox_manager.spinbox.pack(side=LEFT) transpose_frame = Frame(control_frame, padx=8) transpose_frame.pack(side=LEFT) Label(transpose_frame, text="Transpose").pack(side=LEFT) self.transpose_spinbox_manager = SpinboxManager( transpose_frame, self, 'phrase.transpose', ) self.transpose_spinbox_manager.spinbox.pack(side=LEFT) self.v_point_type = StringVar() self.v_point_type.set('Note') OptionMenu( control_frame, self.v_point_type, 'Note', 'Rest', ).pack(side=LEFT) self.canvas = Canvas(self.toplevel, width=600, height=400) self.canvas.pack(side=BOTTOM) # Maps a Point to the ID of its handle, which is a rectangle on the # canvas. self._point_handles = {} # Maps a tuple of two Points to the ID of the line connecting them on # the canvas. self._point_lines = {} # Maps a Point to the line to its next Point that is currently played. self._playing_lines = {} # A set of dotted lines marking the grid on the canvas. self._grid_lines = set() super(PhraseEditor, self).__init__( phrase=phrase, use_grid=True, **kwargs ) def find_point(x,y): """ @return: the point at the specified position on the canvas. """ s = self.point_handle_size for point in self.phrase.points: px,py = point.pos if px-s <= x <= px+s and py-s <= y <= py+s: return point return None def snap_to_grid(x,y): """ Rounds the given coordinates to the grid defined by L{PhraseEditor.grid_resolution}. """ res = self.grid_resolution return round(x/float(res))*res, round(y/float(res))*res def button_pressed(event): """ When the left mouse button is pressed over a point, it becomes the L{PhraseEditor.selected_point}, which can be moved around by L{button_motion()}. If there is no point under the mouse pointer, a new point is appended to the L{Phrase}. """ x = self.canvas.canvasx(event.x) y = self.canvas.canvasy(event.y) point = find_point(x,y) if point is None: if self.use_grid: x,y = snap_to_grid(x,y) point = Point( pos=(int(x),int(y)), type=self.v_point_type.get(), ) self.phrase.points.append(point) self.selected_point = point self.canvas.bind('<Button-1>', button_pressed) def button_motion(event): """ If the mouse is moved while the left or miffle mouse button is held down and a point is selected, this point is moved to the current mouse pointer position. """ if self.selected_point is None: return x = self.canvas.canvasx(event.x) y = self.canvas.canvasy(event.y) if self.use_grid: x,y = snap_to_grid(x,y) canvas_config = self.canvas.config() canvas_width = int(canvas_config['width'][-1]) canvas_height = int(canvas_config['height'][-1]) self.selected_point.pos = ( min(canvas_width, max(0, int(x))), min(canvas_height, max(0, int(y))) ) self.canvas.bind('<B1-Motion>', button_motion) self.canvas.bind('<B2-Motion>', button_motion) def button_released(event): """ When releasing the left or middle mouse button, the currently selected point is deselected. """ self.selected_point = None self.canvas.bind('<ButtonRelease-1>', button_released) self.canvas.bind('<ButtonRelease-2>', button_released) def right_button_pressed(event): """ Pressing the right mouse button over a point removes it from the L{Phrase}. """ x = self.canvas.canvasx(event.x) y = self.canvas.canvasy(event.y) point = find_point(x,y) if point is not None: self.phrase.points.remove(point) self.canvas.bind('<Button-3>', right_button_pressed) def middle_button_pressed(event): if self.selected_point is not None: return x = self.canvas.canvasx(event.x) y = self.canvas.canvasy(event.y) point = find_point(x,y) if point is None: return new_point = Point(pos=point.pos, type=self.v_point_type.get()) self.phrase.points.insert( self.phrase.points.index(point)+1, new_point ) self.selected_point = new_point self.canvas.bind('<Button-2>', middle_button_pressed) def close(self): """ Closes the editor, destroying its Toplevel window. """ #del self.phrase #del self.selected_point #del self._point_handles #del self._point_lines #del self._playing_lines self.toplevel.destroy() def _add_point_handle(self, point): """ Adds a point handle for the given point to the canvas. """ s = self.point_handle_size px, py = point.pos self._point_handles[point] = self.canvas.create_rectangle( px-s,py-s, px+s,py+s, ) def _remove_point_handle(self, point): """ Removes the point handle for the given point. """ self.canvas.delete(self._point_handles[point]) del self._point_handles[point] def _add_point_line(self, point1, point2): """ Adds a line between two points on the canvas. """ px1, py1 = point1.pos px2, py2 = point2.pos self._point_lines[ (point1, point2) ] = self.canvas.create_line( px1,py1, px2,py2, dash=[2,2] if point2.type == 'Rest' else None ) def _remove_point_line(self, point1, point2): """ Removes the line between two given points. """ px1, py1 = point1.pos px2, py2 = point2.pos self.canvas.delete(self._point_lines[(point1, point2)]) del self._point_lines[(point1, point2)] def _remove_point_lines(self): for points, line in self._point_lines.iteritems(): self.canvas.delete(line) self._point_lines = {} def _remove_point_handles(self): for point, handle in self._point_handles.iteritems(): self.canvas.delete(handle) self._point_handles = {} @on_trait_change('phrase, phrase:points') def _points_changed(self, obj, name, old, new): if self.phrase is None: return self._remove_point_handles() self._remove_point_lines() points = self.phrase.points for i, point in enumerate(points): self._add_point_handle(point) if i > 0: self._add_point_line(points[i-1], point) @on_trait_change('phrase:points:pos') def _point_pos_changed(self, point, name, old, new): """ When a point's position changes, its handle and lines to its surrounding points are redefined. """ self._remove_point_handle(point) self._add_point_handle(point) points = self.phrase.points assert point in points i = points.index(point) if i > 0: source_point = points[i-1] self._remove_point_line(source_point, point) self._add_point_line(source_point, point) if i < len(points)-1: target_point = points[i+1] self._remove_point_line(point, target_point) self._add_point_line(point, target_point) @on_trait_change('phrase.name') def _phrase_name_changed(self): """ When the name of the phrase changes, the window title is update. """ if self.phrase is None: return self.toplevel.title("Phrase: %s" % self.phrase.name) def add_playing_point(self, point, color): if point in self._playing_lines: self.remove_playing_point(point, color) if point not in self.phrase.points: return px,py, px2,py2 = self.phrase.get_line(point) self._playing_lines[point] = self.canvas.create_line( px,py, px2,py2, fill=color, width=2.0, dash=[2,2] if point.type == 'Rest' else None ) def remove_playing_point(self, point, color): if point not in self._playing_lines: return self.canvas.delete(self._playing_lines[point]) del self._playing_lines[point] @on_trait_change('use_grid, grid_resolution') def _grid_changed(self): """ Draws a grid if L{PhraseEditor.use_grid} is True, otherwise removes it. """ for rect in self._grid_lines: self.canvas.delete(rect) self._grid_lines.clear() if self.use_grid: config = self.canvas.config() w = int(config['width'][-1]) h = int(config['height'][-1]) res = self.grid_resolution for y in range(0, h, res): self._grid_lines.add(self.canvas.create_line( 0,y, w,y, dash=[1,res-1], fill="#666666" ))
class MSTM_studio: splash_time = 0.5 # time to show splash window, seconds def __init__(self, top=None): '''This class configures and populates the toplevel window. top is the toplevel containing window.''' top.withdraw() time_start = time.time() splash = sup.SplashWindow(top) self.style = ttk.Style() if sys.platform == 'win32': self.style.theme_use('winnative') self.style.configure('.', font='TkDefaultFont') #~ top.geometry('838x455+364+117') top.geometry('850x440') top.title('MSTM studio') #~ top.configure(highlightcolor='black') self.load_images() self.root_panedwin = ttk.Panedwindow(top, orient='horizontal') self.root_panedwin.place(relx=0.0, rely=0.0, relheight=1.0, relwidth=1.0) self.root_panedwin.configure(width=200) self.left_frame = ttk.Frame(width=220.0) self.root_panedwin.add(self.left_frame) #~ self.middle_frame = ttk.Labelframe(width=350, text='View') self.middle_frame = ttk.Frame(width=350) self.root_panedwin.add(self.middle_frame) self.right_frame = ttk.Frame() self.root_panedwin.add(self.right_frame) self.__funcid0 = self.root_panedwin.bind('<Map>', self.__adjust_sash0) self.left_panedwin = ttk.Panedwindow(self.left_frame, orient='vertical') self.left_panedwin.place(relx=0.0, rely=0.0, relheight=1.0, relwidth=1.0) self.left_panedwin.configure(width=200) self.materials_frame = ttk.Labelframe(height=105, text='Materials') self.left_panedwin.add(self.materials_frame) self.spheres_frame = ttk.Labelframe(text='Spheres') self.left_panedwin.add(self.spheres_frame) self.__funcid1 = self.left_panedwin.bind('<Map>', self.__adjust_sash1) self.style.configure('Treeview.Heading', font='TkDefaultFont') self.stvMaterial = ScrolledTreeView(self.materials_frame) self.stvMaterial.place(relx=0.0, y=30, relheight=0.8, relwidth=1.0) self.configure_stvMaterial() self.stvMaterial.bind('<Double-1>', sup.btChangeMatColClick) self.btAddMat = ttk.Button(self.materials_frame, command=sup.btAddMatClick, text='A', image=self.imAdd) self.btAddMat.place(x=5, y=0, height=25, width=25) self.btLoadMat = ttk.Button(self.materials_frame, command=sup.btLoadMatClick, text='L', image=self.imLoad) self.btLoadMat.place(x=30, y=0, height=25, width=25) self.btPlotMat = ttk.Button(self.materials_frame, command=sup.btPlotMatClick, text='P', image=self.imPlot) self.btPlotMat.place(x=55, y=0, height=25, width=25) self.btDelMat = ttk.Button(self.materials_frame, command=sup.btDelMatClick, text='D', image=self.imDelete) self.btDelMat.place(relx=1, x=-30, rely=0, height=25, width=25) self.stvSpheres = ScrolledTreeView(self.spheres_frame) self.stvSpheres.place(relx=0.0, y=30, relheight=0.85, relwidth=1.0) self.configure_stvSpheres() self.stvSpheres.bind('<Double-1>', sup.btEditSphClick) self.btAddSph = ttk.Button(self.spheres_frame, command=sup.btAddSphClick, text='A', image=self.imAdd) self.btAddSph.place(x=5, y=0, height=25, width=25) self.btEditSph = ttk.Button(self.spheres_frame, command=sup.btEditSphClick, text='E', image=self.imEdit) self.btEditSph.place(x=30, y=0, height=25, width=25) self.btPlotSph = ttk.Button(self.spheres_frame, command=sup.btPlotSphClick, text='R', image=self.imRefresh) self.btPlotSph.place(x=55, y=0, height=25, width=25) self.lbEnvMat = ttk.Label(self.spheres_frame, text='Matrix') self.lbEnvMat.place(relx=0.45, y=-5) self.cbEnvMat = ttk.Combobox(self.spheres_frame) self.cbEnvMat.place(relx=0.45, y=10, width=55) self.btDelSph = ttk.Button(self.spheres_frame, command=sup.btDelSphClick, text='D', image=self.imDelete) self.btDelSph.place(relx=1.0, y=0, x=-30, height=25, width=25) self.middle_panedwin = ttk.Panedwindow(self.middle_frame, orient='vertical') self.middle_panedwin.place(relx=0.0, rely=0.0, relheight=1.0, relwidth=1.0) #~ self.middle_panedwin.configure(relwidth=1.0) self.canvas_frame = ttk.Labelframe(height=360, text='View') self.middle_panedwin.add(self.canvas_frame) self.spectrum_frame = ttk.Labelframe(height=-40, text='Spectrum') self.middle_panedwin.add(self.spectrum_frame) self.__funcid2 = self.left_panedwin.bind('<Map>', self.__adjust_sash2) self.canvas = Canvas(self.canvas_frame) self.canvas.place(relx=0.0, rely=0, relheight=1.0, relwidth=1.0) self.canvas.configure(background='white') self.canvas.configure(borderwidth='2') self.canvas.configure(relief='ridge') self.canvas.configure(selectbackground='#c4c4c4') self.canvas.bind('<Button-4>', sup.mouse_wheel) # for Linux self.canvas.bind('<Button-5>', sup.mouse_wheel) # for Linux self.canvas.bind('<MouseWheel>', sup.mouse_wheel) # for Windowz self.canvas.bind('<Button-3>', sup.mouse_down) self.canvas.bind('<B3-Motion>', sup.mouse_move) self.canvas.bind('<ButtonRelease-3>', sup.mouse_up) self.lbZoom = ttk.Label( self.canvas, text='x1.00', background='white') #font=('courier', 18, 'bold'), width=10) self.lbZoom.place(relx=1.0, x=-50, rely=1.0, y=-25) self.lbLambdaMin = ttk.Label(self.spectrum_frame, text='min') self.lbLambdaMin.place(x=5, y=0) self.edLambdaMin = ttk.Entry(self.spectrum_frame) self.edLambdaMin.place(x=5, y=15, width=35) self.edLambdaMin.insert(0, '300') self.lbLambdaMax = ttk.Label(self.spectrum_frame, text='max') self.lbLambdaMax.place(x=45, y=0) self.edLambdaMax = ttk.Entry(self.spectrum_frame) self.edLambdaMax.place(x=45, y=15, width=35) self.edLambdaMax.insert(0, '800') self.lbLambdaCount = ttk.Label(self.spectrum_frame, text='count') self.lbLambdaCount.place(x=85, y=0) self.edLambdaCount = ttk.Entry(self.spectrum_frame) self.edLambdaCount.place(x=85, y=15, width=35) self.edLambdaCount.insert(0, '51') self.btCalcSpec = ttk.Button(self.spectrum_frame, command=sup.btCalcSpecClick, text='Calculate', image=self.imCalc, compound='left') self.btCalcSpec.place(x=130, y=10, width=90, height=25) self.lbSpecScale = ttk.Label(self.spectrum_frame, text='scale') self.lbSpecScale.place(relx=1, x=-115, y=0) self.edSpecScale = ttk.Entry(self.spectrum_frame) self.edSpecScale.place(relx=1, x=-115, y=15, width=50) self.edSpecScale.insert(0, '1') self.btSaveSpec = ttk.Button(self.spectrum_frame, command=sup.btSaveSpecClick, text='S', image=self.imSave) self.btSaveSpec.place(relx=1, x=-55, y=10, width=25, height=25) self.btPlotSpec = ttk.Button(self.spectrum_frame, command=sup.btPlotSpecClick, text='P', image=self.imPlot) self.btPlotSpec.place(relx=1, x=-30, y=10, width=25, height=25) self.right_panedwin = ttk.Panedwindow(self.right_frame, orient='vertical') self.right_panedwin.place(relx=0.0, rely=0.0, relheight=1.0, relwidth=1.0) self.right_panedwin.configure(width=200) self.plot_frame = ttk.Labelframe(height=200, text='Plot') self.right_panedwin.add(self.plot_frame) self.contribs_frame = ttk.Labelframe(height=150, text='Other contributions') self.right_panedwin.add(self.contribs_frame) self.fitting_frame = ttk.Labelframe(height=-50, text='Fitting') self.right_panedwin.add(self.fitting_frame) self.__funcid3 = self.right_panedwin.bind('<Map>', self.__adjust_sash3) # CONTRIBUTIONS self.btAddContrib = ttk.Button(self.contribs_frame, command=sup.btAddContribClick, text='A', image=self.imAdd) self.btAddContrib.place(x=5, y=0, height=25, width=25) self.btPlotAllContribs = ttk.Button(self.contribs_frame, command=sup.btPlotAllContribsClick, text='P', image=self.imPlot) self.btPlotAllContribs.place(x=30, y=0, height=25, width=25) self.btDelContrib = ttk.Button(self.contribs_frame, command=sup.btDelContribClick, text='D', image=self.imDelete) self.btDelContrib.place(relx=1.0, y=0, x=-30, height=25, width=25) self.cbContribs = [] self.edContribs = [] # actually, it will be the list of lists [[]] self.btPlotsContrib = [] self.contribs_list = [ 'ConstBkg', 'LinearBkg', 'LorentzBkg', 'Mie single', 'Mie LN', 'Lorentz peak', 'Gauss peak', 'Au film', 'bst-3Au/glass' ] self.cbContribMats = [] self.btContribDistribPlots = [] # Fitting frame self.edExpFileName = ttk.Entry(self.fitting_frame, text='Exp. file name') self.edExpFileName.place(x=5, y=0, height=25, relwidth=0.8) self.btLoadExp = ttk.Button(self.fitting_frame, command=sup.btLoadExpClick, text='L', image=self.imLoad) self.btLoadExp.place(relx=1.0, x=-55, y=0, height=25, width=25) self.btPlotExp = ttk.Button(self.fitting_frame, command=sup.btPlotExpClick, text='P', image=self.imPlot) self.btPlotExp.place(relx=1.0, x=-30, y=0, height=25, width=25) self.btStartFit = ttk.Button(self.fitting_frame, command=sup.btStartFitClick, text='>', image=self.imPlay) self.btStartFit.place(x=5, y=30, height=25, width=25) self.btStopFit = ttk.Button(self.fitting_frame, command=sup.btStopFitClick, text='|', image=self.imStop) self.btStopFit.place(x=30, y=30, height=25, width=25) self.lbChiSq = ttk.Label(self.fitting_frame, text='ChiSq:') self.lbChiSq.place(x=60, y=35) self.btConstraints = ttk.Button(self.fitting_frame, command=sup.btConstraintsClick, text='Constraints...') self.btConstraints.place(relx=1, x=-100, y=30, height=25, width=95) self._create_menu(top) time_delta = time.time() - time_start # in seconds if time_delta < self.splash_time: time.sleep(self.splash_time - time_delta) top.deiconify() splash.destroy() def configure_stvMaterial(self): self.stvMaterial.configure(columns='Col1') self.stvMaterial.heading('#0', text='MatID') self.stvMaterial.heading('#0', anchor='center') self.stvMaterial.column('#0', width='46') self.stvMaterial.column('#0', minwidth='20') self.stvMaterial.column('#0', stretch='1') self.stvMaterial.column('#0', anchor='w') self.stvMaterial.heading('Col1', text='Name') self.stvMaterial.heading('Col1', anchor='center') self.stvMaterial.column('Col1', width='150') self.stvMaterial.column('Col1', minwidth='20') self.stvMaterial.column('Col1', stretch='1') self.stvMaterial.column('Col1', anchor='w') def configure_stvSpheres(self): self.stvSpheres.configure(columns='Col1 Col2 Col3 Col4 Col5') self.stvSpheres.heading('#0', text='ID') self.stvSpheres.heading('#0', anchor='center') self.stvSpheres.column('#0', width='34') self.stvSpheres.column('#0', minwidth='20') self.stvSpheres.column('#0', stretch='1') self.stvSpheres.column('#0', anchor='w') self.stvSpheres.heading('Col1', text='R') self.stvSpheres.heading('Col1', anchor='center') self.stvSpheres.column('Col1', width='37') self.stvSpheres.column('Col1', minwidth='20') self.stvSpheres.column('Col1', stretch='1') self.stvSpheres.column('Col1', anchor='w') self.stvSpheres.heading('Col2', text='X') self.stvSpheres.heading('Col2', anchor='center') self.stvSpheres.column('Col2', width='31') self.stvSpheres.column('Col2', minwidth='20') self.stvSpheres.column('Col2', stretch='1') self.stvSpheres.column('Col2', anchor='w') self.stvSpheres.heading('Col3', text='Y') self.stvSpheres.heading('Col3', anchor='center') self.stvSpheres.column('Col3', width='34') self.stvSpheres.column('Col3', minwidth='20') self.stvSpheres.column('Col3', stretch='1') self.stvSpheres.column('Col3', anchor='w') self.stvSpheres.heading('Col4', text='Z') self.stvSpheres.heading('Col4', anchor='center') self.stvSpheres.column('Col4', width='34') self.stvSpheres.column('Col4', minwidth='20') self.stvSpheres.column('Col4', stretch='1') self.stvSpheres.column('Col4', anchor='w') self.stvSpheres.heading('Col5', text='mID') self.stvSpheres.heading('Col5', anchor='center') self.stvSpheres.column('Col5', width='32') self.stvSpheres.column('Col5', minwidth='20') self.stvSpheres.column('Col5', stretch='1') self.stvSpheres.column('Col5', anchor='w') def load_images(self): def tryload(fn): try: im = ImageTk.PhotoImage(file=os.path.normpath( os.path.join(os.path.dirname(__file__), 'images', fn))) except Exception as err: print('Can not load %s\n%s' % (fn, err)) return None return im self.imLoad = tryload('folder_open_icon&16.png') self.imDelete = tryload('delete_icon&16.png') self.imPlot = tryload('chart_bar_icon&16.png') self.imPlot2 = tryload('chart_bar2_icon&16.png') self.imAdd = tryload('sq_plus_icon&16.png') self.imSave = tryload('save_icon&16.png') self.imRefresh = tryload('refresh_icon&16.png') self.imExport = tryload('export_icon&16.png') self.imImport = tryload('import_icon&16.png') self.imPlay = tryload('playback_play_icon&16.png') self.imStop = tryload('playback_stop_icon&16.png') self.imCalc = tryload('cogs_icon&16.png') self.imEdit = tryload('doc_edit_icon&16.png') self.imExit = tryload('on-off_icon&16.png') self.imBrush = tryload('brush_icon&16.png') self.imZoomIn = tryload('round_plus_icon&16.png') self.imZoomOut = tryload('round_minus_icon&16.png') def __adjust_sash0( self, event): # mysterious functions left from previous civilizations paned = event.widget pos = [ 220, 575, ] i = 0 for sash in pos: paned.sashpos(i, sash) i += 1 paned.unbind('<map>', self.__funcid0) del self.__funcid0 def __adjust_sash1(self, event): paned = event.widget pos = [ 145, ] i = 0 for sash in pos: paned.sashpos(i, sash) i += 1 paned.unbind('<map>', self.__funcid1) del self.__funcid1 def __adjust_sash2(self, event): paned = event.widget pos = [ 200, ] i = 0 for sash in pos: paned.sashpos(i, sash) i += 1 paned.unbind('<map>', self.__funcid2) del self.__funcid2 def __adjust_sash3(self, event): paned = event.widget pos = [ 200, ] i = 0 for sash in pos: paned.sashpos(i, sash) i += 1 paned.unbind('<map>', self.__funcid3) del self.__funcid3 def _create_menu(self, top): self.menubar = Menu(top) self.filemenu = Menu(self.menubar, tearoff=0) self.filemenu.add_command(label='Import spheres...', command=sup.btImportSpheres, image=self.imImport, compound='left') self.filemenu.add_command(label='Export spheres...', command=sup.btExportSpheres, image=self.imExport, compound='left') self.filemenu.add_separator() self.filemenu.add_command(label='Exit', command=sup.destroy_window, image=self.imExit, compound='left') self.menubar.add_cascade(label='File', menu=self.filemenu) self.matmenu = Menu(self.menubar, tearoff=0) self.matmenu.add_command(label='Add constant...', command=sup.btAddMatClick, image=self.imAdd, compound='left') self.matmenu.add_command(label='Load function...', command=sup.btLoadMatClick, image=self.imLoad, compound='left') self.matmenu.add_separator() self.matmenu.add_command(label='Delete selected', command=sup.btDelMatClick, image=self.imDelete, compound='left') self.matmenu.add_separator() self.matmenu.add_command(label='Plot selected', command=sup.btPlotMatClick, image=self.imPlot, compound='left') self.matmenu.add_separator() self.matmenu.add_command(label='Change view color...', command=sup.btChangeMatColClick, image=self.imBrush, compound='left') self.menubar.add_cascade(label='Materials', menu=self.matmenu) self.sphmenu = Menu(self.menubar, tearoff=0) self.sphmenu.add_command(label='Add...', command=sup.btAddSphClick, image=self.imAdd, compound='left') self.sphmenu.add_separator() self.sphmenu.add_command(label='Edit selected...', command=sup.btEditSphClick, image=self.imEdit, compound='left') self.sphmenu.add_command(label='Delete selected', command=sup.btDelSphClick, image=self.imDelete, compound='left') self.sphmenu.add_separator() self.sphmenu.add_command(label='Generate on mesh...', command=sup.btGenerateSpheresClick) self.menubar.add_cascade(label='Spheres', menu=self.sphmenu) self.viewmenu = Menu(self.menubar, tearoff=0) self.viewmenu.add_command(label='Zoom in', command=lambda: sup.mouse_wheel( type('', (), { 'num': 4, 'delta': 0 })()), image=self.imZoomIn, compound='left') self.viewmenu.add_command(label='Zoom out', command=lambda: sup.mouse_wheel( type('', (), { 'num': 5, 'delta': 0 })()), image=self.imZoomOut, compound='left') self.viewmenu.add_command(label='Reset view', command=sup.btPlotSphClick, image=self.imRefresh, compound='left') self.menubar.add_cascade(label='View', menu=self.viewmenu) self.opticsmenu = Menu(self.menubar, tearoff=0) self.opticsmenu.add_command(label='Calculate', command=sup.btCalcSpecClick, image=self.imCalc, compound='left') self.menubar.add_cascade(label='Spectrum', menu=self.opticsmenu) self.fittingmenu = Menu(self.menubar, tearoff=0) self.fittingmenu.add_command(label='Load experiment...', command=sup.btLoadExpClick, image=self.imLoad, compound='left') self.fittingmenu.add_separator() self.fittingmenu.add_command(label='Constraints...', command=sup.btConstraintsClick) self.fittingmenu.add_separator() self.fittingmenu.add_command(label='Start fit', command=sup.btStartFitClick, image=self.imPlay, compound='left') self.fittingmenu.add_command(label='Stop fit', command=sup.btStopFitClick, image=self.imStop, compound='left') self.menubar.add_cascade(label='Fitting', menu=self.fittingmenu) self.helpmenu = Menu(self.menubar, tearoff=0) self.helpmenu.add_command(label='About', command=sup.btAboutClick) self.menubar.add_cascade(label='Help', menu=self.helpmenu) # display the menu top.config(menu=self.menubar)
class Viewer(Frame): def __init__(self, master,x=600,y=200, onLeft=None, onRight=None, **kwargs): self.root=master self.xsize=x self.ysize=y self.onLeft=onLeft self.onRight=onRight self.ratio=100. Frame.__init__(self, master,width=x,height=y, **kwargs) self.canvas = Canvas(self, width=x, height=y, background="white") self.xsb = Scrollbar(self, orient="horizontal", command=self.canvas.xview) self.ysb = Scrollbar(self, orient="vertical", command=self.canvas.yview) self.canvas.configure(yscrollcommand=self.ysb.set, xscrollcommand=self.xsb.set) self.canvas.configure(scrollregion=(0,0,x,y)) self.xsb.grid(row=1, column=0, sticky="ew") self.ysb.grid(row=0, column=1, sticky="ns") self.canvas.grid(row=0, column=0, sticky="nsew") self.grid_rowconfigure(0, weight=1) self.grid_columnconfigure(0, weight=1) self.canvas.bind("<Button-1>", self.clickL) self.canvas.bind("<Button-3>", self.clickR) # This is what enables using the mouse: self.canvas.bind("<ButtonPress-1>", self.move_start) self.canvas.bind("<B1-Motion>", self.move_move) #linux scroll self.canvas.bind("<Button-4>", self.zoomerP) self.canvas.bind("<Button-5>", self.zoomerM) self.canvas.bind_all("<Prior>", self.zoomerP) self.canvas.bind_all("<Next>", self.zoomerM) self.canvas.bind_all("E", self.zoomExtens) #windows scroll self.canvas.bind_all("<MouseWheel>",self.zoomer) def reset(self): pass def set_title(self, title): self.root.title( title) #move def move_start(self, event): self.canvas.scan_mark(event.x, event.y) return True def move_move(self, event): self.canvas.scan_dragto(event.x, event.y, gain=1) return True #windows zoom def zoomer(self,event): if (event.delta > 0): self.ratio *= 1.1 elif (event.delta < 0): self.ratio *= 0.9 self.redraw() def redraw(self): self.canvas.delete("all") self.canvas.configure(scrollregion = self.canvas.bbox("all")) def zoomExtens(self, *args): x0,y0,x1,y1 = self.canvas.bbox("all") xlen=x1-x0 ylen=y1-y0 height=self.canvas.winfo_height() width=self.canvas.winfo_width() unfit=min(width/float(xlen), height/float(ylen)) self.ratio*=unfit self.redraw() # """" if xlen and ylen: self ratio*= self.canvas.scale("all", xlen/2., ylen/2., float(self.xsize)/xlen, float(self.ysize)/ylen) self.canvas.configure(scrollregion = self.canvas.bbox("all")) """ #linux zoom def zoomerP(self,event): self.canvas.scale("all", event.x, event.y, 1.1, 1.1) self.canvas.configure(scrollregion = self.canvas.bbox("all")) def zoomerM(self,event): self.canvas.scale("all", event.x, event.y, 0.9, 0.9) self.canvas.configure(scrollregion = self.canvas.bbox("all")) def pose2p(self, pose): x,y=pose[:2] return int(x*self.ratio), -int(y*self.ratio) def line2p(self, line): if type(line[0]) in (float, int): line=zip(line[::2],line[1::2]) return map(self.pose2p, line) def p2m(self, x, y): return x/self.ratio, -y/self.ratio def create_line(self, coords, **kwargs): return self.canvas.create_line(self.line2p(coords), **kwargs) def create_polygon(self, coords, **kwargs): return self.canvas.create_polygon(self.line2p(coords), **kwargs) def delete(self, object): self.canvas.delete(object) def clickL(self, event): if self.onLeft: x,y=self.p2m(int(self.canvas.canvasx(event.x)), int(self.canvas.canvasy(event.y))) self.onLeft(x,y) return True def clickR(self, event): if self.onRight: x,y=self.p2m(int(self.canvas.canvasx(event.x)), int(self.canvas.canvasy(event.y))) self.onRight(x,y) return True