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 initUI(self): self.parent.title("Shapes") self.pack(fill=BOTH, expand=1) canvas = Canvas(self) canvas.create_oval(10, 10, 80, 80, outline="red", fill="green", width=2) #Here the create_oval() method is used to create a circle item. #The first four parameters are the bounding box coordinates of the circle. #In other words, they are x and y coordinates of the top-left and bottom-right points of the box, #in which the circle is drawn. canvas.create_oval(110, 10, 210, 80, outline="#f11", fill="#1f1", width=2) canvas.create_rectangle(230, 10, 290, 60, outline="#f11", fill="#1f1", width=2) #We create a rectangle item. #The coordinates are again the bounding box of the rectangle to be drawn. canvas.create_arc(30, 200, 90, 100, start=0, extent=210, outline="#f11", fill="#1f1", width=2) #This code line creates an arc. #An arc is a part of the circumference of the circle. #We provide the bounding box. #The start parameter is the start angle of the arc. #The extent is the angle size. points = [150, 100, 200, 120, 240, 180, 210, 200, 150, 150, 100, 200] canvas.create_polygon(points, outline='red', fill='green', width=2) #A polygon is created. #It is a shape with multiple corners. #To create a polygon in Tkinter, we provide the list of polygon coordinates to the create_polygon() method. canvas.pack(fill=BOTH, expand=1)
def error_and_exit(title, main_text): """ Show a pop-up window and sys.exit() out of Python. :param title: the short error description :param main_text: the long error description """ # NOTE: We don't want to load all of these imports normally. # Otherwise we will have these unused GUI modules loaded in the main process. from Tkinter import Tk, Canvas, DISABLED, INSERT, Label, Text, WORD root = Tk() root.wm_title("Tribler: Critical Error!") root.wm_minsize(500, 300) root.wm_maxsize(500, 300) root.configure(background='#535252') Canvas(root, width=500, height=50, bd=0, highlightthickness=0, relief='ridge', background='#535252').pack() pane = Canvas(root, width=400, height=200, bd=0, highlightthickness=0, relief='ridge', background='#333333') Canvas(pane, width=400, height=20, bd=0, highlightthickness=0, relief='ridge', background='#333333').pack() Label(pane, text=title, width=40, background='#333333', foreground='#fcffff', font=("Helvetica", 11)).pack() Canvas(pane, width=400, height=20, bd=0, highlightthickness=0, relief='ridge', background='#333333').pack() main_text_label = Text(pane, width=45, height=6, bd=0, highlightthickness=0, relief='ridge', background='#333333', foreground='#b5b5b5', font=("Helvetica", 11), wrap=WORD) main_text_label.tag_configure("center", justify='center') main_text_label.insert(INSERT, main_text) main_text_label.tag_add("center", "1.0", "end") main_text_label.config(state=DISABLED) main_text_label.pack() pane.pack() root.mainloop()
def initUI(self): # Setting title as wordle self.parent.title("Wordle") self.pack(fill=BOTH, expand=1) #print "Inside Canvas", self.arg # Task 5 - Pad outside border by 50 pixels all around # Canvas with 50 pixels outside border canvas = Canvas(self, bd=50, bg = "white") # Two helper variables # for generating start position of a word # Task 6 - Random color for each word # Generating Random colors for each of the word for word, value in self.arg.items(): # Task 7 - Font size based on frequency of the words # Generating font size based on the frequency of the words! # Very simple logic # Could make it more complex but didn't do that! if value > 15: i = random.randrange(150,400, 70) j = random.randrange(150,600, 50) else: i = random.randrange(200,600, 27) j = random.randrange(100,600, 33) canvas.create_text(i, j, anchor=W, font=("times",(value*2)), text=word, fill=choice(COLORS)) canvas.pack(fill=BOTH, expand=1)
class GUI: def __init__(self, title, width, height): from Tkinter import Tk, Canvas, Toplevel self.width = width self.height = height self.title = title self.app = Tk() self.app.withdraw() self.win = Toplevel() self.win.wm_title(title) self.canvas = Canvas(self.win, width=(self.width * 2), height=(self.height * 2)) self.canvas.pack(side='bottom', expand="yes", anchor="n", fill='both') self.win.winfo_toplevel().protocol('WM_DELETE_WINDOW', self.close) #self.canvas.bind("<Configure>", self.changeSize) def close(self): self.app.destroy() def draw(self, lat, length): print "Drawing...", for h in range(length): for w in range(self.width): if lat.data[h][w]: self.canvas.create_rectangle(w * 2, h * 2, w * 2 + 2, h * 2 + 2, fill="black") self.win.update_idletasks() print "Done!"
def init_ui(self): """ """ self.parent.title("Worm") self.pack(fill=BOTH, expand=1) canvas = Canvas(self) # horizontal lines this_row_height = 0 for row in range(0, self.grid_width - 1): this_row_height += self.row_height canvas.create_line(0, this_row_height, self.width, this_row_height) # vertical lines this_column_width = 0 for column in range(0, self.grid_height-1): this_column_width += self.col_width canvas.create_line(this_column_width, 0, this_column_width, self.height) # pop a circle in every box for x in range(0, self.grid_width): for y in range(0, self.grid_height): self.add_circle(canvas, x, y) canvas.pack(fill=BOTH, expand=1)
class KeyboardView(Frame): INPUT_KEYS = 'q2w3er5t6y7ui9o0pzsxdcfvbhnjm' def __init__(self, master, instrument=None): Frame.__init__(self, master) self.instrument = instrument self.canvas = Canvas(self, width=KEYBOARD_WIDTH, height=KEYBOARD_HEIGHT, background='gray', highlightthickness=0 ) self.canvas.pack() self.keyboard_keys = {} for tone in range(MIN_TONE, MAX_TONE): self.keyboard_keys[tone] = self.create_key(tone) self.running = True self._worker() def _worker(self): if not self.running: return for k in self.keyboard_keys.values(): k.work() self.after(UPDATE_INTERVAL, self._worker) def set_instrument(self, new_instrument): # print "set_instrument: %s" % str(new_instrument) for key in self.keyboard_keys.values(): key.release() old_instrument = self.instrument self.instrument = new_instrument if not old_instrument is None: old_instrument.off() def create_key(self, tone): x0 = tone * KEY_WIDTH y0 = 0 key = Key(tone, self, self.canvas, x0, y0) self.canvas.tag_bind(key.widget, "<Button-1>", key.press) self.canvas.tag_bind(key.widget, "<ButtonRelease-1>", key.release) if 0 <= tone < len(self.INPUT_KEYS): input_key = self.INPUT_KEYS[tone] self.bind_all("<Key-%s>" % input_key, key.press) self.bind_all("<KeyRelease-%s>" % input_key, key.release) return key def destroy(self): self.running = False return Frame.destroy(self)
def draw(sequence): screen = Tk() w = Canvas(screen, width=480, height = 480) w.pack() w.create_oval(80,80,160,160,fill="green") w.create_oval(80 +120,80,160 +120,160, fill="green") w.create_oval(80 +240,80,160 +240,160, fill="green") w.create_oval(80,80 +120,160,160+120,fill="green") w.create_oval(80 +120,80 +120,160 +120,160+120, fill="green") w.create_oval(80 +240,80+120,160 +240,160+120, fill="green") w.create_oval(80,80 +240,160,160+240,fill="green") w.create_oval(80 +120,80 +240,160 +120,160+240, fill="green") w.create_oval(80 +240,80+240,160 +240,160+240, fill="green") pos_dict = {"1":(120,120), "2":(240,120), "3":(360,120), "4":(120,240), "5":(240,240), "6":(360,240), "7":(120,360), "8":(240,360), "9":(360,360)} for i in range(len(sequence)-1): x1 = pos_dict[sequence[i]][0] y1 = pos_dict[sequence[i]][1] x2 = pos_dict[sequence[i+1]][0] y2 = pos_dict[sequence[i+1]][1] w.create_line(x1,y1,x2,y2,arrow="last",fill="red",width="5") mainloop()
def main(): cWidth = 1280 cHeight = 800 #leap-sets up the leap stuff leapControl = Leap.Controller() leapControl.set_policy_flags(Leap.Controller.POLICY_BACKGROUND_FRAMES) theListener = TouchPointListener() leapControl.add_listener(theListener) #tkinter-create base widget for Tkinter master = Tk() master.title( "Touch Points" ) #tkinter-add a canvas widget to the base widget, For a description of tkinter canvas api see: #http://effbot.org/tkinterbook/canvas.htm paintCanvas = Canvas(width = cWidth, height = cHeight ) paintCanvas.pack() #leap-adds the canvas to the Listener object theListener.set_canvas(paintCanvas) #tkinterstarts the Tkinter main loop and destroys it when the window is closed #note theres weirdness here that I didn't care about becuase it's going away eventually master.mainloop() master.destroy()
class SimpleGrid(Frame): def __init__(self, parent, props): Frame.__init__(self,parent) self.parent = parent self.iWidth = props['width'] self.iHeight = props['height'] self.nCols = props['cols'] self.nRows = props['rows'] self.gWidthPercent = 0.90 self.gHeightPercent = 0.90 self.gridSqWidth = 0 self.gridSqHeight = 0 self.gridX = 0 self.gridY = 0 self.initGrid() def initGrid(self): self.parent.title("SimpleGrid") self.pack(fill=BOTH, expand=1) self.buildCanvas() self.calculateDimensions() self.enableEvents() def calculateDimensions(self): # calculate the size of the grid squares self.gridSqWidth = (self.gWidthPercent * self.iWidth) / self.nCols self.gridSqHeight = (self.gHeightPercent * self.iHeight) / self.nRows # calculate the upper left corner self.gridX = (1.0 - self.gWidthPercent) * self.iWidth / 2.0 self.gridY = (1.0 - self.gHeightPercent) * self.iHeight / 2.0 def buildCanvas(self): self.canvas = Canvas(self) def draw(self): for i in range(0,self.nRows): for j in range(0,self.nCols): self.drawSquare(i,j) self.canvas.pack(fill=BOTH, expand=1) def drawSquare(self,row,col): sqX = self.gridX + (self.gridSqWidth*col) sqY = self.gridY + (self.gridSqHeight*row) self.canvas.create_rectangle(sqX, sqY, sqX + self.gridSqWidth, sqY + self.gridSqHeight, outline="black") def enableEvents(self): # do nothing -- let child classes do this return
class ScrolledCanvas(Frame): """ A scrolling canvas of frames with checkboxes. """ def __init__(self, master, name=None, scrollregion=(0, 0, '5i', '5i'), items=[], window_size=[160, 30], **canvaskw): Frame.__init__(self, master, name=name) self.scrollcanvas = Canvas(self, name='scrollcanvas', scrollregion=scrollregion, **canvaskw) self.yscroll = Scrollbar(self, name='yscroll', command=self.scrollcanvas.yview) self.scrollcanvas['yscrollcommand'] = self.yscroll.set self.yscroll.pack(side=RIGHT, fill=Y) self.scrollcanvas.pack(side=LEFT, fill=BOTH, expand=YES) self.items = dict.fromkeys(items) for n, i in enumerate(items): self.items[i] = {'frame': Frame(self, name=(i.lower() + '_frame'))} self.items[i]['frame'].config(relief=GROOVE, padding=5) self.items[i]['chbx'] = Checkbutton(self.items[i]['frame'], name=(i.lower() + '_chbx')) self.items[i]['chbx']['text'] = i self.items[i]['chbx'].pack(side=LEFT, fill=X) y = window_size[1] / 2 + window_size[1] * n self.items[i]['window'] = self.scrollcanvas.create_window(0, y) self.scrollcanvas.itemconfigure(self.items[i]['window'], window=self.items[i]['frame'], anchor=W, width=window_size[0], height=window_size[1])
class CoordsCanvas(object): def __init__(self, parent, **kwargs): self._canvas = Canvas(parent, **kwargs) self._canvas.pack(fill=BOTH, expand=YES) self._canvas.bind("<Double-Button-1>", self.on_double_click) self._canvas.bind("<Shift-Button-1>", self.on_shift_button_click) self._canvas.bind("<Control-Button-1>", self.on_ctrl_button_click) self._canvas.bind("<Alt-Button-1>", self.on_alt_button_click) self._canvas.bind("<Option-Button-1>", self.on_alt_button_click) self._canvas.bind("<Double-Button-1>", self.on_double_click) self._canvas.bind("<ButtonPress-1>", self.on_button_press) self._canvas.bind("<ButtonRelease-1>", self.on_button_release) self._event_receiver = None self._dragger = Dragger() def on_double_click(self, _): if hasattr(self._event_receiver, 'zoom_in'): self._event_receiver.zoom_in() def on_shift_button_click(self, _): if hasattr(self._event_receiver, 'zoom_out'): self._event_receiver.zoom_out() def on_ctrl_button_click(self, event): if hasattr(self._event_receiver, 'add'): self._event_receiver.add(event.x, event.y) def on_alt_button_click(self, event): if hasattr(self._event_receiver, 'remove'): self._event_receiver.remove(event.x, event.y) def on_button_press(self, event): self._dragger.start(event.x, event.y) def on_button_release(self, event): if hasattr(self._event_receiver, 'move'): self._dragger.drag_to( event.x, event.y, self._event_receiver.move) def create_circle(self, x, y, r, **kwargs): return self._canvas.create_oval(x-r, y-r, x+r, y+r, **kwargs) def create_text(self, x, y, **kwargs): return self._canvas.create_text(x, y, **kwargs) def get_width(self): return self._canvas.winfo_reqwidth() def get_height(self): return self._canvas.winfo_reqheight() def set_event_receiver(self, receiver): self._event_receiver = receiver def destroy(self, item): self._canvas.delete(item) def destroy_all(self): self._canvas.delete("all")
class gridDisplay(Frame): def __init__(self, parent, board): """ Initialize an instance of the board within the TKinter hierarchy. Draws the game grid and fills it in with the current state of the board as passed into it by the displayBoard method. Numbers part of the goal configuration are displayed in blue, the rest in black. """ Frame.__init__(self, parent) self.parent = parent self.board = board self.pack(fill=BOTH) self.canvas = Canvas(self, width = WIDTH, height = HEIGHT) self.canvas.pack(fill=BOTH, side=TOP) for i in xrange(4): color = "red" if (i == 0 or i == 3) else "gray" #Color the grid boundaries red. x0 = x1 = MARGIN + i * SIDE y0 = MARGIN y1 = HEIGHT - MARGIN self.canvas.create_line(x0, y0, x1, y1, fill=color) self.canvas.create_line(y0, x0, y1, x1, fill=color) for i in xrange(3): for j in xrange(3): answer = self.board[i][j] #Current state of board at i,j if answer != 0: x = MARGIN + j * SIDE + SIDE / 2 y = MARGIN + i * SIDE + SIDE / 2 original = goalConfiguration[i][j] #Goal state of board at i, j color = "blue" if answer == original else "black" #Number printed in blue if part of goal state, black if not. self.canvas.create_text(x, y, text=answer, tags="numbers", fill=color)
def expired(cur_dir, amount): """ Displays a "deadline expired" picture """ root = Tk() root.focus_set() # Get the size of the screen and place the splash screen in the center img = Image.open(str(cur_dir) + '/Images/Expired.gif') width = img.size[0] height = img.size[1] flog = root.winfo_screenwidth()/2-width/2 blog = root.winfo_screenheight()/2-height/2 root.overrideredirect(True) root.geometry('%dx%d+%d+%d' % (width*1, height + 44, flog, blog)) # Pack a canvas into the top level window. # This will be used to place the image expired_canvas = Canvas(root) expired_canvas.pack(fill="both", expand=True) # Open the image imgtk = PhotoImage(img) # Get the top level window size # Need a call to update first, or else size is wrong root.update() cwidth = root.winfo_width() cheight = root.winfo_height() # create the image on the canvas expired_canvas.create_image(cwidth/2, cheight/2.1, image=imgtk) Button(root, text='Deadline Expired by ' + str(amount ) + '. Assignment Submitted, time '\ 'noted', width=80, height=2, command=root.destroy).pack() root.after(5000, root.destroy) root.mainloop()
def success(cur_dir): """ Displays a "successful submission" picture """ root = Tk() root.focus_set() # Get the size of the screen and place the splash screen in the center img = Image.open(str(cur_dir) + '/Images/Success.gif') width = img.size[0] height = img.size[1] flog = (root.winfo_screenwidth()/2-width/2) blog = (root.winfo_screenheight()/2-height/2) root.overrideredirect(1) root.geometry('%dx%d+%d+%d' % (width, height, flog, blog)) # Pack a canvas into the top level window. # This will be used to place the image success_canvas = Canvas(root) success_canvas.pack(fill = "both", expand = True) # Open the image imgtk = PhotoImage(img) # Get the top level window size # Need a call to update first, or else size is wrong root.update() cwidth = root.winfo_width() cheight = root.winfo_height() # create the image on the canvas success_canvas.create_image(cwidth/2, cheight/2, image = imgtk) root.after(4000, root.destroy) root.mainloop()
def initUI(self): self.parent.title("Lines") self.pack(fill=BOTH, expand=1) canvas = Canvas(self) for a in range(0, len(lines)): line = lines[a] canvas.create_line([line["x1"], line["y1"]], [line["x2"], line["y2"]]) count = 1 for i in range(0, 10): pathh = nx.dijkstra_path(G, path[i - 1], path[i]) for a in range(0, len(pathh) - 1): line = {} resize = 5000 currentNode = allNodes[pathh[a]] nextNode = allNodes[pathh[a + 1]] left = 44.7240 bottom = 48.7435 line["y1"] = 500 - int( (float(currentNode["h"]) - bottom) * resize) line["x1"] = int((float(currentNode["w"]) - left) * resize) line["y2"] = 500 - int( (float(nextNode["h"]) - bottom) * resize) line["x2"] = int((float(nextNode["w"]) - left) * resize) canvas.create_line([line["x1"], line["y1"]], [line["x2"], line["y2"]], fill="red", width=count) count = count + 1 canvas.pack(fill=BOTH, expand=1)
def initUI(self): self.parent.title("Layout Test") self.config(bg = '#F0F0F0') self.pack(fill = BOTH, expand = 1) #create canvas canvas1 = Canvas(self, relief = FLAT, background = "#D2D2D2", width = 180, height = 500) canvas1.pack(side = TOP, anchor = NW, padx = 10, pady = 10) #add quit button button1 = Button(canvas1, text = "Quit", command = self.quit, anchor = W) button1.configure(width = 10, activebackground = "#ee0000", relief = FLAT) button1.pack(side = TOP) button2 = Button(canvas1, text = "Start", command = self.print_out, anchor = W) button2.configure(width = 10, activebackground = "#00ee00", relief = FLAT) button2.pack(side = TOP)
class CanvasFrame(Frame): def __initialize_canvas(self): self.__canvas = Canvas(self.master, width=Constants.DEFAULT_FRAME_WIDTH() + 120, height=Constants.DEFAULT_FRAME_HEIGHT()) self.__canvas.pack() self.pack() def __setup_timer(self): RefreshTimer(self.master, 10, self) MonsterTimer(self.master, 1000) def __setup_handlers(self): ArrowHandler(self.master) KeyMovementHandler(self.master) MouseClickHandler(self.master) def refresh(self): self.__canvas.delete('all') BoardPrinter.print_board(self.__canvas) SelectPrinter.print_selected(self.__canvas) TurnMenuPrinter.print_turn_menu(self.__canvas) def __init__(self): Frame.__init__(self, Tk()) self.pack() self.__initialize_canvas() self.__setup_timer() self.__setup_handlers()
class LandscapeGUI(Frame): def __init__(self, parent): self.HEIGHT = 1000 self.WIDTH = 1000 self.parent = parent self.parent.title("MAZE") self.canvas = Canvas(height=self.HEIGHT, width=self.WIDTH, bg='white') self.canvas.pack(fill=BOTH, expand=True) def paint_map(self, matrix): deltax = self.HEIGHT / len(matrix) deltay = self.WIDTH / len(matrix[0]) rows = len(matrix) cols = len(matrix[0]) for i in range(0, rows): for j in range(0, cols): if (matrix[i][j] == Terrain.FLAT): _cell_color = 'white' elif (matrix[i][j] == Terrain.HILLY): _cell_color = 'grey' elif (matrix[i][j] == Terrain.FOREST): _cell_color = 'pink' else: _cell_color = 'green' self._paint_cell(i, j, _cell_color, deltax, deltay) def _paint_cell(self, rw, cl, color, deltax, deltay): x0 = cl * deltax x1 = x0 + deltax y0 = rw * deltay y1 = y0 + deltay self.canvas.create_rectangle(x0, y0, x1, y1, fill=color, tags="cursor")
class CanvasFrame(Frame): def initializeCanvas(self): self.canvas = Canvas(self.master, width=200, height=100) self.canvas.pack() self.pack() def setup_timer(self): self.x = 10 self.y = 10 self.timer_tick() def timer_tick(self): self.canvas.delete('all') self.canvas.create_line(self.x, self.y, 50, 50) self.x = self.x + 1 self.y = self.y + 2 print 'in loop' print self.x print self.y self.master.after(1000, self.timer_tick) def __init__(self): Frame.__init__(self, Tk()) self.pack() self.initializeCanvas() self.setup_timer()
def __init_window(self, height, width): self.master.title = "Ray Py" canvas = Canvas(self.master, width=width, height=height) canvas.pack(side=TOP) self.img = PhotoImage(width=width, height=height) canvas.create_image((width / 2, height / 2), image=self.img, state="normal") self.startButton = Button(self.master, text="Render", command=lambda: self.__onStartPressed()) self.startButton.pack(side=RIGHT) self.resetButton = Button(self.master, text="Reset", command=lambda: self.__onResetPressed()) self.resetButton.config(state="disabled") self.resetButton.pack(side=RIGHT) self.listbox = Listbox(self.master, height=5) self.listbox.bind('<<ListboxSelect>>', self.__selectTracer) self.listbox.insert(END, "Simple", "Shadow", "ShadingShadow", "Recursive", "PathTracer") self.listbox.pack(side=LEFT) self.listbox.selection_set(0) self.listbox.activate(0) self.listbox.focus_set()
def main(): global pd, image, photo, canvas, image_on_canvas, master, args logging.info("Loading petri dish...") pd = load(args.file) # Start the petri dish execution thread t = Thread(target=updateModel, args=()) t.start() if (args.nogui == True): signal.signal(signal.SIGINT, signalHandler) signal.pause() else: image = petriDishToImage( pd, config.IMAGE_RESIZE) # Generate the first image to get the size master = Tk() canvas = Canvas(master, width=image.width, height=image.height) canvas.pack() photo = ImageTk.PhotoImage(image) image_on_canvas = canvas.create_image(0, 0, image=photo, anchor=tk.NW) updateView() master.protocol("WM_DELETE_WINDOW", onDeleteWindow) master.mainloop()
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=Tkinter.VERTICAL) vscrollbar.pack(fill=Tkinter.Y, side=Tkinter.RIGHT, expand=Tkinter.FALSE) hscrollbar = Scrollbar(self, orient=Tkinter.HORIZONTAL) hscrollbar.pack(fill=Tkinter.X, side=Tkinter.BOTTOM, expand=Tkinter.FALSE) canvas = Canvas(self, bd=0, highlightthickness=0, yscrollcommand=vscrollbar.set, xscrollcommand=hscrollbar.set) canvas.pack(side=Tkinter.LEFT, fill=Tkinter.BOTH, expand=Tkinter.TRUE) vscrollbar.config(command=canvas.yview) hscrollbar.config(command=canvas.xview) # 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=Tkinter.NW) # 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 = (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): ''' _configure_canvas is used to resize the window size to fit content. Can be used when changing window. ''' 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())
def show(self): root = Tk() canvas = Canvas(root, width=self.layout.width, height=self.layout.height) self.layout.layout() self.draw_page_sets(canvas, self.layout.page_set) canvas.pack() root.mainloop()
def main(): root = Tk() # w, h = root.winfo_screenwidth(), root.winfo_screenheight() w, h = 960, 540 # get value from arduino # ser = serial.Serial('/dev/tty.usbserial', 9600) pos = 0 root.overrideredirect(1) root.focus_set() root.bind("<Escape>", lambda e: e.widget.quit()) root.geometry("%dx%d+300+300" % (w, h)) canvas = Canvas(root, width=w, height=h, background="black") rect0 = canvas.create_rectangle(w/2-75, h/2-20, w/2+75, h/2+20, fill="#05f", outline="#05f") rect1 = canvas.create_rectangle(w/2-20, h/2-75, w/2+20, h/2+75, fill="#05f", outline="#05f") canvas.pack() while (True): # gets angle and moves accordingly # pos = ser.readline() canvas.move(rect0, 1, 0) canvas.move(rect1, 1, 0) root.update() root.after(30) app = App(root) time.sleep(0.5) root.mainloop()
class VertCanvas(Frame): def __init__(self, parent): Frame.__init__(self, parent, background="white") self.parent = parent self.canvas = Canvas(self) self.canvas.pack(fill=BOTH, expand=1)
def __init__(self): canvas = Canvas(self.root, width=220, height=220) corner1 = self.corner1 corner2 = self.corner2 canvas.create_oval(corner1.x, corner1.y, corner2.x, corner2.y,\ fill = "white", width = 3) center = self.centerPoint() def createTickMark(angle, dFromCenter, length, mark): angle -= 90.0 rads = radians(angle) p1 = center.offsetByVector(rads, dFromCenter) p2 = center.offsetByVector(rads, dFromCenter + length) mark(p1, p2) sm_Tick = lambda p1, p2: canvas.create_line(p1.x, p1.y, p2.x, p2.y) lg_Tick = lambda p1, p2: canvas.create_line(p1.x, p1.y, p2.x, p2.y,\ fill = 'red', width=3) for angle in range(0, 360, 6): createTickMark(angle, 90, 9, sm_Tick) for angle in range(0, 360, 30): createTickMark(angle, 80, 19, lg_Tick) for angle in range(0, 360, 90): createTickMark(angle, 60, 10, sm_Tick) canvas.pack() self.root.wm_title("Relógio Analógico") self.updateClock(canvas)
class Visualizer(object): def __init__(self, toplevel, **kwargs): self.toplevel = toplevel self.canvas = Canvas( self.toplevel, width=600, height=400, background='black' ) self.canvas.pack() self._playing_lines = {} def add_point(self, phrase, point, color): if point in self._playing_lines: self.remove_point(phrase, point) if point.type == 'Rest': return if point not in phrase.points: return px,py, px2,py2 = phrase.get_line(point) self._playing_lines[point] = self.canvas.create_line( px,py, px2,py2, fill=color ) def remove_point(self, phrase, point): if point not in self._playing_lines: return self.canvas.delete(self._playing_lines[point]) del self._playing_lines[point]
def buildDisplay(self): winWidth = 1000 winHeight = 800 frame = Frame(self.root, width=winWidth, height=winHeight) frame.pack(side=TOP, expand=YES, fill=X) c = Canvas(frame, width=winWidth, height=winHeight, scrollregion=(0, 0, self.canvasWidth, self.canvasHeight)) hbar = Scrollbar(frame, orient=HORIZONTAL) hbar.pack(side=BOTTOM, fill=X) hbar.config(command=c.xview) vbar = Scrollbar(frame, orient=VERTICAL) vbar.pack(side=RIGHT, fill=Y) vbar.config(command=c.yview) c.config(xscrollcommand=hbar.set, yscrollcommand=vbar.set) c.pack(side=LEFT, expand=YES, fill=BOTH) self.canvas = c editFrame = Frame(self.root, width=winWidth, height=0) editFrame.pack(side=BOTTOM, fill=X) self.editFrame = editFrame
def __init__(self): canvas = Canvas(self.root, width=220, height=220) #Get the corners of the circle corner1 = self.corner1 corner2 = self.corner2 canvas.create_oval(corner1.x, corner1.y, corner2.x, corner2.y,\ fill = "white", width = 3) center = self.centerPoint() def createTickMark(angle, dFromCenter, length, mark): angle -= 90.0 rads = radians(angle) p1 = center.offsetByVector(rads, dFromCenter) p2 = center.offsetByVector(rads, dFromCenter + length) mark(p1, p2) #mark is meant to be one of the below lambdas sm_Tick = lambda p1, p2: canvas.create_line(p1.x, p1.y, p2.x, p2.y) lg_Tick = lambda p1, p2: canvas.create_line(p1.x, p1.y, p2.x, p2.y,\ fill = 'red', width=3) #Create minute tick marks for angle in range(0, 360, 6): createTickMark(angle, 90, 9, sm_Tick) #Create hour tick marks for angle in range(0, 360, 30): createTickMark(angle, 80, 19, lg_Tick) #Create extra marks every 3 hours for angle in range(0, 360, 90): createTickMark(angle, 60, 10, sm_Tick) canvas.pack() self.root.wm_title("Clock") #Prepare the code to be run in the main loop self.updateClock(canvas)
def main(): master = Tk() w = Canvas(master, width=WIDTH, height=HEIGHT) w.pack() img = PhotoImage(width=WIDTH, height=HEIGHT, master=master) w.create_image((WIDTH/2, HEIGHT/2), image=img, state="normal") cam = Camera() cam.look_at(np.array([0, 10, -8]), np.array([0, 0, 3.0]), np.array([0, 1.0, 0])) init_world(world_objects) init_light(light_objects) # Generate rays for each pixel and determine color progress_interval = HEIGHT*WIDTH / 10 progress_tick = 0 print 'Progress (10 ticks): [ -', sys.stdout.flush() for y in xrange(HEIGHT): for x in xrange(WIDTH): progress_tick += 1 if progress_tick > progress_interval: progress_tick = 0 print ' -', sys.stdout.flush() ray = compute_camera_ray(WIDTH, HEIGHT, cam, 3, x, y) color = trace_ray(world_objects, light_objects, ray) # TKinter requires a hex string as color input for photo image img.put('#%02X%02X%02X' % tuple(color), (x, y)) print ' ]' mainloop()
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()
class Ex(Frame): def __init__(self,parent): Frame.__init__(self,parent) self.parent = parent self.x_before = 20 self.x_current = 20 self.y_before = 200 self.y_current = 200 self.initUI() self.runRandWalk(70) def initUI(self): self.parent.title("Random Walk Lines 1") self.pack(fill=BOTH,expand=1) self.canvas = Canvas(self) self.canvas.create_line(10,10,390,10) self.canvas.create_line(10,10,10,390) self.canvas.create_line(10,390,390,390) self.canvas.create_line(390,10,390,390) self.canvas.create_line(10,200,390,200,dash=(4,2), width=2) self.canvas.pack(fill=BOTH,expand=1) def RandWalk(self): r = random.randint(0,1) addval = 0; if r == 0: addval = ADDVAL else: addval = -ADDVAL self.y_current = self.y_before + addval self.x_current = self.x_before + XSTEP if self.y_current < 200: if self.y_before == 200: self.canvas.create_line(self.x_before,self.y_before, self.x_current,self.y_current, fill = "green", width = 5) else: self.canvas.create_line(self.x_before,self.y_before, self.x_current,self.y_current, fill = "green", width = 5) else: if self.y_before<200: self.canvas.create_line(self.x_before,self.y_before, self.x_current,self.y_current, fill = "green", width = 5) else: self.canvas.create_line(self.x_before,self.y_before, self.x_current,self.y_current, fill = "red", width = 5) self.canvas.pack(fill=BOTH,expand=1) self.x_before = self.x_current self.y_before = self.y_current def runRandWalk(self,steps): for x in range(0,steps): self.RandWalk()
def _setupDisplay(self, root, config): """Set screen size and add background image root -- the Tk instance of the application config -- ConfigParser containing application settings """ fullscreen = config.getboolean(ini.general, ini.fullscreen) bgimage = ini.getPath(config.get(ini.general, ini.bgimage)) image = Image.open(bgimage) backgroundIm = ImageTk.PhotoImage(image) if(fullscreen): screenwidth = root.winfo_screenwidth() screenheight = root.winfo_screenheight() (w, h) = image.size self._scalefactor = (screenwidth / float(w), screenheight / float(h)) image = image.resize((screenwidth, screenheight)) else: (screenwidth, screenheight) = image.size self._scalefactor = (1, 1) geom = "{}x{}+{}+{}".format(screenwidth, screenheight, 0, 0) root.geometry(geom) root.overrideredirect(1) background = Canvas(root, width = screenwidth, height = screenheight) self._canvas = background background.pack() backgroundIm = ImageTk.PhotoImage(image) self._backgroundIm = backgroundIm background.create_image(0,0, image = backgroundIm, anchor = NW)
class App: ticklist = [] # seznam funkcí, které se budou spouštět při tiku tick_id = None # identifikárot následujícího ticku def __init__(self, root, width=80, height=60, grid=10, tick=200): self.root = root # objekt okna self.width = width # šířka, jako počet sloupců self.height = height # výška, jako počet řádků self.grid = grid # kolik pixelů má jeden čtverec sítě self.tick = tick # počet milisekund pro jeden úder hodin root.title("had.py") # titulek okna self.canvas = Canvas(root, bg='white', width=grid*width, height=grid*height) self.canvas.pack() root.bind("<Escape>", self.destroy) root.after(self.tick, self.tickej) def tickej(self): for f in self.ticklist: f() self.tick_id = self.root.after(self.tick, self.tickej) def tick_register(self, fnc): self.ticklist.append(fnc) def destroy(self, event=None): self.root.after_cancel(self.tick_id) root.destroy()
class Move(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.initUI() self.animate() def initUI(self): self.parent.title("Move") self.pack(fill=BOTH, expand=1) self.canvas = Canvas(self) self.oval = self.canvas.create_oval(40, 10, 110, 80, outline="black", width=2) self.canvas.pack(fill=BOTH, expand=1) def animate(self): location = self.canvas.coords(self.oval) self.canvas.coords(self.oval, location[0] + 2.5, location[1], location[2] + 2.5, location[3]) self.after(1000, self.animate)
def __init__(self, drs, size_canvas=True, canvas=None): """ :param drs: ``AbstractDrs``, The DRS to be drawn :param size_canvas: bool, True if the canvas size should be the exact size of the DRS :param canvas: ``Canvas`` The canvas on which to draw the DRS. If none is given, create a new canvas. """ master = None if not canvas: master = Tk() master.title("DRT") font = Font(family='helvetica', size=12) if size_canvas: canvas = Canvas(master, width=0, height=0) canvas.font = font self.canvas = canvas (right, bottom) = self._visit(drs, self.OUTERSPACE, self.TOPSPACE) width = max(right + self.OUTERSPACE, 100) height = bottom + self.OUTERSPACE canvas = Canvas(master, width=width, height=height) #, bg='white') else: canvas = Canvas(master, width=300, height=300) canvas.pack() canvas.font = font self.canvas = canvas self.drs = drs self.master = master
def initUI(self): self.parent.title("TNN visualization") self.pack(fill=BOTH, expand=1) canvas = Canvas(self, bg="#000") width, height = 500, 500 canvas.config(width=width, height=height) canvas.create_line(400, 0, 0, 400, width=1, fill="#fff") data = clusterize_data() #for i in range(30): # x, y = randint(1, height), randint(1, height) # canvas.create_oval(x, y, x+4, y+4, outline="#0f0", fill="#0f0") min, max = -3, 3 range_data = max - min step = 500.0 / range_data for d in data: x, y = (max - d[0]) * step, (max - d[1]) * step x, y = 500 - x, 500 - y canvas.create_oval(x, y, x + 4, y + 4, outline="#0f0", fill="#0f0") canvas.pack(fill=BOTH, expand=1)
class TronCanvas(object): """ Tron canvas class, contains the fields related to drawing the game. Canvas is used to draw the Players on the screen. The drawing is done by Tk. Attributes: - Root -- The root Tk instance - Canvas -- The TkCanvas - Bike width -- Width of the bike in pixels - Rows -- Number of cells in each row of the board. The Bike width x Rows + 2 x MARGIN gives the size in pixels of the canvas. MARGIN The margin of the canvas DELAY Delay time between redrawing the canvas GUI_DISPLAY_AFTER_COLLISION Time in seconds GUI is displayed after a collision. Default is 2 seconds """ # Margin of canvas in pixels MARGIN = 5 # Delay between updates in milliseconds DELAY = 150 # Time GUI is displayed after a collision GUI_DISPLAY_AFTER_COLLISION = 2 def __init__(self, rows, bike_width): """ Constructor :param rows: number of rows on the grid :type rows: int :param bike_width: width of bike when drawing :type bike_width: int """ # Create Tk instance self.root = Tk() # Set window to be resizable self.root.resizable(width=0, height=0) # Canvas to draw on canvas_width = 2 * TronCanvas.MARGIN + rows * bike_width canvas_height = canvas_width # Create a Tk Canvas instance self.tk_canvas = Canvas(self.root, width=canvas_width, height=canvas_height) # Geometry manager organizes widgets in blocks before placing # them in the parent widget self.tk_canvas.pack() # Set bike width self.bike_width = bike_width # Set bike height self.bike_height = bike_width # Set number of rows self.rows = rows
class GUI: def __init__(self, title, width, height): from Tkinter import Tk, Canvas, Toplevel self.width = width self.height = height self.title = title self.app = Tk() self.app.withdraw() self.win = Toplevel() self.win.wm_title(title) self.canvas = Canvas(self.win, width=(self.width * 2), height=(self.height * 2)) self.canvas.pack(side = 'bottom', expand = "yes", anchor = "n", fill = 'both') self.win.winfo_toplevel().protocol('WM_DELETE_WINDOW',self.close) #self.canvas.bind("<Configure>", self.changeSize) def close(self): self.app.destroy() def draw(self, lat, length): print "Drawing...", for h in range(length): for w in range(self.width): if lat.data[h][w]: self.canvas.create_rectangle(w*2, h*2, w*2+2, h*2+2, fill = "black") self.win.update_idletasks() print "Done!"
def run_pinballview(width, height, configuration): """ Changed from original Pierre-Luc Bacon implementation to reflect the visualization changes in the PinballView Class. """ width, height = float(width), float(height) master = Tk() master.title('RLPY Pinball') screen = Canvas(master, width=500.0, height=500.0) screen.configure(background='LightGray') screen.pack() environment = PinballModel(configuration) environment_view = PinballView(screen, width, height, environment) actions = [ PinballModel.ACC_X, PinballModel.DEC_Y, PinballModel.DEC_X, PinballModel.ACC_Y, PinballModel.ACC_NONE ] done = False while not done: user_action = np.random.choice(actions) environment_view.blit() if environment.episode_ended(): done = True if environment.take_action(user_action) == environment.END_EPISODE: done = True environment_view.blit() screen.update()
def plot(text, words, rowheight=15, rowwidth=800): """ Generate a lexical dispersion plot. @param text: The source text @type text: C{list} or C{enum} of C{str} @param words: The target words @type words: C{list} of C{str} @param rowheight: Pixel height of a row @type rowheight: C{int} @param rowwidth: Pixel width of a row @type rowwidth: C{int} """ canvas = Canvas(width=rowwidth, height=rowheight*len(words)) text = list(text) scale = float(rowwidth)/len(text) position = 0 for word in text: for i in range(len(words)): x = position * scale if word == words[i]: y = i * rowheight canvas.create_line(x, y, x, y+rowheight-1) position += 1 canvas.pack() canvas.mainloop()
def __init__(self, drs, size_canvas=True, canvas=None): """ :param drs: C{AbstractDrs}, The DRS to be drawn :param size_canvas: bool, True if the canvas size should be the exact size of the DRS :param canvas: C{Canvas} The canvas on which to draw the DRS. If none is given, create a new canvas. """ master = None if not canvas: master = Tk() master.title("DRT") font = Font(family='helvetica', size=12) if size_canvas: canvas = Canvas(master, width=0, height=0) canvas.font = font self.canvas = canvas (right, bottom) = self._visit(drs, self.OUTERSPACE, self.TOPSPACE) width = max(right+self.OUTERSPACE, 100) height = bottom+self.OUTERSPACE canvas = Canvas(master, width=width, height=height)#, bg='white') else: canvas = Canvas(master, width=300, height=300) canvas.pack() canvas.font = font self.canvas = canvas self.drs = drs self.master = master
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 __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 Example(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.x0=[x*0.1 for x in range(10, 15)] self.y0=[0 for x in range(10, 15)] #self.tet1 = [i for i in range(90)] #self.tet2 = [i for i in range(45, 135)] self.tet1_con = 0 self.tet2_con = 0 self.count1 = 0 self.count2 = 0 self.sign1 = 1 self.sign2 = -1 self.parent = parent self.initUI() self.parent.after(0, self.animation) def initUI(self): self.parent.title("Arm") self.pack(fill=BOTH, expand=1) self.canvas = Canvas(self) #self.canvas.create_line(0, 0, 200, 100+self.count, width=arm_width) line = Line(self.canvas, points['1'], (800/2, 400)) arms.append(line) line = Line(self.canvas, 90-(points['2']-points['1']), line.cor1) arms.append(line) self.canvas.pack(fill=BOTH, expand=1) def animation(self): self.canvas.delete("all") #self.canvas.create_line(0, 0, 200, 100+self.count, width=arm_width) '''if points['1'] > 90 and self.sign1 == 1: self.sign1 = -1 elif points['1'] == 45 and self.sign1 == -1: self.sign1 = 1 if points['2'] > 135 and self.sign2 == 1: self.sign2 = -1 elif points['2'] == 90 and self.sign2 == -1: self.sign2 = 1 points['2']+=self.sign2 points['1']+=self.sign1''' if self.count1 >= len(self.x0) and self.sign1 == 1: self.sign1 = -1 if self.count1 <= 0 and self.sign1 == -1: self.sign1 = 1 self.count1+=self.sign1 tet1, tet2 = getAngles(self.x0[self.count1-1], self.y0[self.count1-1]) print tet1, tet2 line = arms[0].draw(tet1) arms[1].draw(90-(tet2+tet1), line, 'red') #line = arms[0].draw(points['1']) #arms[1].draw(90-(points['2']-points['1']), line) self.canvas.update() #self.count +=1 self.parent.after(50, self.animation)
def plot_results(self): grid_x = (self.canvas_width - 2 * self.canvas_margin) / (self.grid_size) grid_y = (self.canvas_height - 2 * self.canvas_margin) / (self.grid_size) pin_dx = grid_x / 6 pin_dy = grid_y / 6 master = Tk() w = Canvas(master, width=self.canvas_width, height=self.canvas_height) w.pack() for node in self.graph: i, j = self.id_to_coord(node) if node[-1] == 's': i += 0.5 j += 0.5 nx, ny = self.get_xy(i, j) if node[-1] == 's': fill_col = 'green' w.create_rectangle(nx - pin_dx, ny - pin_dy, nx + pin_dx, ny + pin_dy, fill=fill_col) else: fill_col = 'black' w.create_oval(nx - 2, ny - 2, nx + 2, ny + 2, fill=fill_col) self.draw_routes(w) w.update() w.postscript(file='sol35.ps', colormode='color') mainloop()
class Grid: def __init__(self, width, height, side=25, title='Grid', background='grey'): tk = Tk() tk.withdraw() top = Toplevel(tk) top.wm_title(title) top.protocol('WM_DELETE_WINDOW', top.destroy) self.width = width self.height = height self.canvas = Canvas(top, width=self.width, height=self.height, background=background) self.canvas.pack() self.side = side self.cells = {} def transform_x(self, x): return self.side * x + self.width / 2. def transform_y(self, y): return self.height - (self.side * y + self.height / 2. ) # Zero y is at the top def draw(self, (x, y), color='white'):
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 plot(text, words, rowheight=15, rowwidth=800): """ Generate a lexical dispersion plot. @param text: The source text @type text: C{list} or C{enum} of C{str} @param words: The target words @type words: C{list} of C{str} @param rowheight: Pixel height of a row @type rowheight: C{int} @param rowwidth: Pixel width of a row @type rowwidth: C{int} """ canvas = Canvas(width=rowwidth, height=rowheight * len(words)) text = list(text) scale = float(rowwidth) / len(text) position = 0 for word in text: for i in range(len(words)): x = position * scale if word == words[i]: y = i * rowheight canvas.create_line(x, y, x, y + rowheight - 1) position += 1 canvas.pack() canvas.mainloop()
class PaintBox(Frame): def __init__(self): Frame.__init__(self) self.place(x=0, y=0) self.leap = Leap.Controller() self.painter = TouchPointListener() self.botonLimpiar = Button(self, text="Limpiar", fg="white", bg="red", command=self.painter.limpiar) self.botonLimpiar.pack(side=TOP) self.botonCapturar = Button(self, text="Identificar Numero", fg="blue", bg="white", command=self.painter.capturar) self.botonCapturar.pack(side=TOP) self.leap.add_listener(self.painter) self.pack(expand=YES, fill=BOTH) self.master.title("Prueba 1") self.master.geometry("500x500+0+0") self.leap.enable_gesture(Leap.Gesture.TYPE_SWIPE) self.leap.config.set("Gesture.Swipe.MinLength", 100.0) self.leap.config.set("Gesture.Swipe.MinVelocity", 750) self.leap.config.save() self.paintCanvas = Canvas(self, width="500", height="500", bg="white") self.paintCanvas.pack() self.painter.set_canvas(self.paintCanvas)
def run_pinballview(width, height, configuration): """ Changed from original Pierre-Luc Bacon implementation to reflect the visualization changes in the PinballView Class. """ width, height = float(width), float(height) master = Tk() master.title('RLPY Pinball') screen = Canvas(master, width=500.0, height=500.0) screen.configure(background='LightGray') screen.pack() environment = PinballModel(configuration) environment_view = PinballView(screen, width, height, environment) actions = [ PinballModel.ACC_X, PinballModel.DEC_Y, PinballModel.DEC_X, PinballModel.ACC_Y, PinballModel.ACC_NONE] done = False while not done: user_action = np.random.choice(actions) environment_view.blit() if environment.episode_ended(): done = True if environment.take_action(user_action) == environment.END_EPISODE: done = True environment_view.blit() screen.update()
class Wall(object): MIN_RED = MIN_GREEN = MIN_BLUE = 0x0 MAX_RED = MAX_GREEN = MAX_BLUE = 0xFF PIXEL_WIDTH = 96 def __init__(self, width, height): self.width = width self.height = height self._tk_init() self.pixels = [(0, 0, 0) for i in range(self.width * self.height)] def _tk_init(self): self.root = Tk() self.root.title("ColorWall %d x %d" % (self.width, self.height)) self.root.resizable(0, 0) self.frame = Frame(self.root, bd=5, relief=SUNKEN) self.frame.pack() self.canvas = Canvas(self.frame, width=self.PIXEL_WIDTH * self.width, height=self.PIXEL_WIDTH * self.height, bd=0, highlightthickness=0) self.canvas.pack() self.root.update() def set_pixel(self, x, y, hsv): self.pixels[self.width * y + x] = hsv def get_pixel(self, x, y): return self.pixels[self.width * y + x] def draw(self): self.canvas.delete(ALL) for x in range(len(self.pixels)): x_0 = (x % self.width) * self.PIXEL_WIDTH y_0 = (x / self.width) * self.PIXEL_WIDTH x_1 = x_0 + self.PIXEL_WIDTH y_1 = y_0 + self.PIXEL_WIDTH hue = "#%02x%02x%02x" % self._get_rgb(self.pixels[x]) self.canvas.create_rectangle(x_0, y_0, x_1, y_1, fill=hue) self.canvas.update() def clear(self): for i in range(self.width * self.height): self.pixels[i] = (0, 0, 0) def _hsv_to_rgb(self, hsv): rgb = colorsys.hsv_to_rgb(*hsv) red = self.MAX_RED * rgb[0] green = self.MAX_GREEN * rgb[1] blue = self.MAX_BLUE * rgb[2] return (red, green, blue) def _get_rgb(self, hsv): red, green, blue = self._hsv_to_rgb(hsv) red = int(float(red) / (self.MAX_RED - self.MIN_RED) * 0xFF) green = int(float(green) / (self.MAX_GREEN - self.MIN_GREEN) * 0xFF) blue = int(float(blue) / (self.MAX_BLUE - self.MIN_BLUE) * 0xFF) return (red, green, blue)
def xGC_skew(seq, window = 1000, zoom = 100, r = 300, px = 100, py = 100): """Calculates and plots normal and accumulated GC skew (GRAPHICS !!!).""" from Tkinter import Scrollbar, Canvas, BOTTOM, BOTH, ALL, \ VERTICAL, HORIZONTAL, RIGHT, LEFT, X, Y yscroll = Scrollbar(orient = VERTICAL) xscroll = Scrollbar(orient = HORIZONTAL) canvas = Canvas(yscrollcommand = yscroll.set, xscrollcommand = xscroll.set, background = 'white') win = canvas.winfo_toplevel() win.geometry('700x700') yscroll.config(command = canvas.yview) xscroll.config(command = canvas.xview) yscroll.pack(side = RIGHT, fill = Y) xscroll.pack(side = BOTTOM, fill = X) canvas.pack(fill=BOTH, side = LEFT, expand = 1) canvas.update() X0, Y0 = r + px, r + py x1, x2, y1, y2 = X0 - r, X0 + r, Y0 -r, Y0 + r ty = Y0 canvas.create_text(X0, ty, text = '%s...%s (%d nt)' % (seq[:7], seq[-7:], len(seq))) ty +=20 canvas.create_text(X0, ty, text = 'GC %3.2f%%' % (GC(seq))) ty +=20 canvas.create_text(X0, ty, text = 'GC Skew', fill = 'blue') ty +=20 canvas.create_text(X0, ty, text = 'Accumulated GC Skew', fill = 'magenta') ty +=20 canvas.create_oval(x1,y1, x2, y2) acc = 0 start = 0 for gc in GC_skew(seq, window): r1 = r acc+=gc # GC skew alpha = pi - (2*pi*start)/len(seq) r2 = r1 - gc*zoom x1 = X0 + r1 * sin(alpha) y1 = Y0 + r1 * cos(alpha) x2 = X0 + r2 * sin(alpha) y2 = Y0 + r2 * cos(alpha) canvas.create_line(x1,y1,x2,y2, fill = 'blue') # accumulated GC skew r1 = r - 50 r2 = r1 - acc x1 = X0 + r1 * sin(alpha) y1 = Y0 + r1 * cos(alpha) x2 = X0 + r2 * sin(alpha) y2 = Y0 + r2 * cos(alpha) canvas.create_line(x1,y1,x2,y2, fill = 'magenta') canvas.update() start += window canvas.configure(scrollregion = canvas.bbox(ALL))
class SimpleGrid(Frame): def __init__(self, parent, props): Frame.__init__(self, parent) self.parent = parent self.iWidth = props['width'] self.iHeight = props['height'] self.nCols = props['cols'] self.nRows = props['rows'] self.gWidthPercent = 0.90 self.gHeightPercent = 0.90 self.gridSqWidth = 0 self.gridSqHeight = 0 self.gridX = 0 self.gridY = 0 self.initGrid() def initGrid(self): self.parent.title("SimpleGrid") self.pack(fill=BOTH, expand=1) self.buildCanvas() self.calculateDimensions() self.enableEvents() def calculateDimensions(self): # calculate the size of the grid squares self.gridSqWidth = (self.gWidthPercent * self.iWidth) / self.nCols self.gridSqHeight = (self.gHeightPercent * self.iHeight) / self.nRows # calculate the upper left corner self.gridX = (1.0 - self.gWidthPercent) * self.iWidth / 2.0 self.gridY = (1.0 - self.gHeightPercent) * self.iHeight / 2.0 def buildCanvas(self): self.canvas = Canvas(self) def draw(self): for i in range(0, self.nRows): for j in range(0, self.nCols): self.drawSquare(i, j) self.canvas.pack(fill=BOTH, expand=1) def drawSquare(self, row, col): sqX = self.gridX + (self.gridSqWidth * col) sqY = self.gridY + (self.gridSqHeight * row) self.canvas.create_rectangle(sqX, sqY, sqX + self.gridSqWidth, sqY + self.gridSqHeight, outline="black") def enableEvents(self): # do nothing -- let child classes do this return
class GUI(object): def __init__(self, world): self.ticks = 0 self.world = world self.width = world.width self.height = world.height self.root = Tk() self.root.title("Mars Explorer") window_x, window_y = self._compute_window_coords() self.root.geometry('%dx%d+%d+%d' % (self.width, self.height, window_x, window_y)) self.canvas = Canvas(self.root, width=self.width, height=self.height) self.canvas.pack() self.canvas.after(1, self._tick) def start(self): self.root.mainloop() def _tick(self): # Stop if done. if self.world.is_done(): return self.world.tick() self._draw() self.ticks += 1 self.canvas.after(1, self._tick) def _draw(self): self.canvas.delete('all') self.world.draw(self.canvas) for entity in self.world.entities: entity.draw(self.canvas) self.canvas.create_text(self.width - 20, 10, text=str(self.ticks)) self.canvas.create_text(self.width - 70, 30, text='Rocks in explorers: %d' % self.world.rocks_in_explorers()) self.canvas.create_text(self.width - 70, 50, text='Rocks delivered: %d' % self.world.rocks_collected) self.canvas.create_text(self.width - 55, 70, text='Total rocks: %d' % self.world.num_rocks) def _compute_window_coords(self): # http://stackoverflow.com/a/14912644/742501 screen_width = self.root.winfo_screenwidth() screen_height = self.root.winfo_screenheight() window_x = screen_width / 2 - self.width / 2 window_y = screen_height / 2 - self.height / 2 return window_x, window_y
class DCGreenLanternWidget(Frame): """ Green Lantern logo from DC comics (yeah yeah, i'm shitty artist, i know) """ green = "#07A007" outline = "#FFFFFF" unpowered = '#C0C0C0' def __init__(self, parent, initial_state): Frame.__init__(self, parent) self.pack(fill=BOTH, expand=1) self.canvas = Canvas(self, cnf={'background': BACKGROUND_COLOR}) # outer circle kw = {'outline': self.outline, 'fill': self.green} base = 30 * SCALE d = 190 * SCALE s = 10 * SCALE outer_circle = ((base, base, base + d - s, base + d), (base + s, base + s, base + d - s - s, base + d - s)) self.canvas.create_oval(*outer_circle[0], **kw) kw['fill'] = BACKGROUND_COLOR self.canvas.create_oval(*outer_circle[1], **kw) # inner circle kw = {'outline': self.outline, 'fill': self.green} base = 70 * SCALE d = 100 * SCALE s = 14 * SCALE outer_circle = ((base, base + s, base + d, base + d), (base + s, base + s + s, base + d - s, base + d - s)) self.canvas.create_oval(*outer_circle[0], **kw) kw['fill'] = initial_state[1] if initial_state[0] else self.unpowered self.item = self.canvas.create_oval(*outer_circle[1], **kw) # top bar self.canvas.create_rectangle(base, base, base + d, base + s, outline=self.green, fill=self.green) # bottom bar self.canvas.create_rectangle(base, base + d, base + d, base + d + s, outline=self.green, fill=self.green) self.canvas.pack(fill=BOTH, expand=1) def change_color(self, color): self.canvas.itemconfig(self.item, outline=color, fill=color)
class CoordsCanvas(object): def __init__(self, parent, **kwargs): self._canvas = Canvas(parent, **kwargs) self._canvas.pack(fill=BOTH, expand=YES) self._canvas.bind("<Double-Button-1>", self.on_double_click) self._canvas.bind("<Shift-Button-1>", self.on_shift_button_click) self._canvas.bind("<Control-Button-1>", self.on_ctrl_button_click) self._canvas.bind("<Alt-Button-1>", self.on_alt_button_click) self._canvas.bind("<Option-Button-1>", self.on_alt_button_click) self._canvas.bind("<Double-Button-1>", self.on_double_click) self._canvas.bind("<ButtonPress-1>", self.on_button_press) self._canvas.bind("<ButtonRelease-1>", self.on_button_release) self._event_receiver = None self._dragger = Dragger() def on_double_click(self, _): if hasattr(self._event_receiver, 'zoom_in'): self._event_receiver.zoom_in() def on_shift_button_click(self, _): if hasattr(self._event_receiver, 'zoom_out'): self._event_receiver.zoom_out() def on_ctrl_button_click(self, event): if hasattr(self._event_receiver, 'add'): self._event_receiver.add(event.x, event.y) def on_alt_button_click(self, event): if hasattr(self._event_receiver, 'remove'): self._event_receiver.remove(event.x, event.y) def on_button_press(self, event): self._dragger.start(event.x, event.y) def on_button_release(self, event): if hasattr(self._event_receiver, 'move'): self._dragger.drag_to(event.x, event.y, self._event_receiver.move) def create_circle(self, x, y, r, **kwargs): return self._canvas.create_oval(x - r, y - r, x + r, y + r, **kwargs) def create_text(self, x, y, **kwargs): return self._canvas.create_text(x, y, **kwargs) def get_width(self): return self._canvas.winfo_reqwidth() def get_height(self): return self._canvas.winfo_reqheight() def set_event_receiver(self, receiver): self._event_receiver = receiver def destroy(self, item): self._canvas.delete(item) def destroy_all(self): self._canvas.delete("all")
def failure(reason, cur_dir): """ Displays a "submission failure" picture and emails a bug report to maintenance. """ bugmail = {"email": "*****@*****.**"} send_email(bugmail, "QR Code Submission Failure", reason, None) root = Tk() root.focus_set() # Get the size of the screen and place the splash screen in the center gif = Image.open(str(cur_dir) + '/Images/Failure.gif') width = gif.size[0] height = gif.size[1] flog = (root.winfo_screenwidth()/2-width/2) blog = (root.winfo_screenheight()/2-height/2) root.overrideredirect(1) root.geometry('%dx%d+%d+%d' % (width*1, height + 44, flog, blog)) # Pack a canvas into the top level window. # This will be used to place the image failure_canvas = Canvas(root) failure_canvas.pack(fill = "both", expand = True) # Open the image imgtk = PhotoImage(gif) # Get the top level window size # Need a call to update first, or else size is wrong root.update() cwidth = root.winfo_width() cheight = root.winfo_height() # create the image on the canvas failure_canvas.create_image(cwidth/2, cheight/2.24, image=imgtk) Button(root, text = str( reason), width = 50, height = 2, command = root.destroy).pack() root.after(5000, root.destroy) root.mainloop()