class Picture(object): def __init__(self, tk_hnd): self._img = None self._hnd = tk_hnd def open_file(self, filename): self._img = PhotoImage(file=filename) self.refresh() def refresh(self): if not self._img: return self._hnd.configure(image=self._img) @property def width(self): if not self._img: return None else: return self._img.width() @property def height(self): if not self._img: return None else: return self._img.height()
def __init__(self, parent): """A game where the player selects a hut to rest. The program initially puts 'enemy' or a 'friend' inside each hut. Some huts could also be left 'unoccupied'. You are asked to select a hut. You win if the hut occupant is either a 'friend' or if the hut is not occupied. :param parent: the parent tkinter widget :ivar list huts: list to store occupant types (as strings) :ivar int hut_width: the width of the application window in pixels :ivar int hut_height: the height of the application window in pixels :ivar PhotoImage village_image: background image for the app :ivar PhotoImage hut_image: the hut image for the radio buttons :ivar Tk container: the main widget serving as a parent for others. In this example it is just the main Tk instance. :ivar str result: the string to declare the result via a messagebox. """ self.village_image = PhotoImage(file="jungle_small.gif") self.hut_image = PhotoImage(file="hut_small.gif") self.hut_width = 40 self.hut_height = 56 self.container = parent self.huts = [] self.result = "" self.occupy_huts() self.setup()
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 __init__(self, master=None, test=False): Frame.__init__(self, master) _ver = __version__.split() self.master.title(" " * 5 + "{} {}".format(_ver[0], _ver[2])) #.master self.pack() # ... why I'm packing here?? coords? self.test = test # images storaging dir_path = dirname(realpath(__file__)) self.img = dict() self.img['logo'] = PhotoImage(file=dir_path + "/img/logo.ppm") self.img['help'] = PhotoImage(file=dir_path + "/img/help.ppm") self.img['file'] = PhotoImage(file=dir_path + "/img/file.ppm") self.img['gear'] = PhotoImage(file=dir_path + "/img/gear.ppm") # body init self.prevailing_body = 0 self.body = None self.MAINVERTEX = [0, 0, 0, 0, 0, 0] # Conversion gathered data container self._convert_ = {'setup': [], 'solvation': []} self._convertdata_ = None # Script part self._script_ = {'mainpage': [], 'advanced': [], 'restrain': []} self.createmainPennon()
def box_filter(self): print "Box filter is used..." box_filter_pic = PhotoImage( width=self.width, height=self.height) # preserve dimensions of orig. img for v in range(0, self.height): for u in range(0, self.width): summe = [0, 0, 0] # create a filter region for every pixel for j in range(-1, 2): # move filter for i in range(-1, 2): if 0 <= u + i < self.width: if 0 <= v + j < self.height: pixel = map( int, self.pixel_matrix[u + i][v + j].split()) summe = [ sum([x, y]) for x, y in zip(pixel, summe) ] else: pixel = map(int, self.pixel_matrix[u][ v - 1].split()) # fill edge pixel summe = [ sum([x, y]) for x, y in zip(pixel, summe) ] else: pixel = map(int, self.pixel_matrix[u - 1] [v].split()) # fill edge pixel summe = [sum([x, y]) for x, y in zip(pixel, summe)] r, g, b = [x / 9.0 for x in summe] box_filter_pic.put("#%02x%02x%02x" % (int(r), int(g), int(b)), (u, v)) print "Done!\n" return box_filter_pic
def __init__(self, parent): """The View component of the Hut Game. This class represents the view component of a MVC architecture. It defines and sets up graphical user interface. In this example, the View has no knowledge of the Controller or the model. However, the Controller sets up the necessary callback functions that are invoked when various events are triggered. :param parent: The parent tkinter widget.In this example it is the instance of Tk class (called mainwin) :ivar int hut_width: The width of the application window in pixels. :ivar int hut_height: The height of the application window in pixels :ivar PhotoImage village_image: Background image for the app :ivar PhotoImage hut_image: The hut image for the radio buttons. :ivar container: The main widget serving as a parent for others. In this example it is just the main Tk instance passed as :ivar str result: The string to declare the result via a messagebox. """ self.village_image = PhotoImage(file="Jungle_small.gif") self.hut_image = PhotoImage(file="Hut_small.gif") self.container = parent # ------------------------------------------------------------------ # Important: Set the hut_width to about 70 pixels if the radio # button is configured with "indicatoron=0" option (i.e. without the # radio button indicator # ------------------------------------------------------------------ self.hut_width = 40 self.hut_height = 56 self.radio_btn_pressed = None
def __init__(self): self._root = Tk() self._window_title = 'uatu-0.0.0' self._window_width = 500 self._window_height = 300 self._window_position = 200 self._run_conditions = 0 self._tk_bb_image_1 = PhotoImage(file='../images/bb-3.png') self._tk_bb_image_2 = PhotoImage(file='../images/bb-2.png') self._loaded_model_text = None # Label(root, text='No model loaded') self._loaded_test_text = None # Label(root, text='No test loaded') self._bb_image_left = None # Label(root, image=tk_bb_image) self._bb_image_right = None # Label(root, image=tk_bb_image) self._run_button = None # Button(root, text='Run', state='disabled') self._step_button = None # Button(root, text='Step', state='disabled') self._reset_button = None # Button(root, text='Stop', state='disabled') self._certainty_text = None # Label(root, text='1.00') self._prediction_text = None # Label(root, text='MATCH') self._is_model_loaded = False self._is_test_loaded = False self._load_model_button = None # Button(gv.root, text='Load Model', command=lambda: load_model_button(gv)).grid(row=0, column=2) self._load_test_button = None # Button(gv.root, text='Load Test', command=lambda: load_test_button(gv)).grid(row=2, column=2) self._model = None self._test = None self._step_position = 0 self._max_position = 0 self._stop_button = None self._stop_press = False self._pred = 0 self._truth_text = None self._all_truth = None self._number_of_data = 200 self._run_speed = 50
class App(object): def __init__(self, update, fps=8): self.t = 0 self.period = 1000/fps self.update = update self.master = Tk() m = self.update(self.t) self.W, self.H = m3d.shape(m) self.img = PhotoImage(width=self.W, height=self.H) canvas = Canvas(self.master, width=self.W, height=self.H) canvas.pack() canvas.create_image((self.W/2, self.H/2), image=self.img, state="normal") self._on_tick() def _on_tick(self): def _formatcolor(c): return '#{0:02X}{1:02X}{2:02X}'.format(*c) m = self.update(self.t) self.img.blank() lines = [] for j in xrange(self.H): line = ' '.join(_formatcolor(m[j][i]) for i in xrange(self.W)) lines.append( '{' + line + '}') self.img.put(' '.join(lines)) self.master.after(self.period, self._on_tick) self.t += self.period def start(self): self.master.mainloop()
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 reset(gv): gv.run_button.config(text='Run', state='disabled') gv.loaded_model_text.config(text='No model loaded') gv.is_model_loaded = False gv.loaded_test_text.config(text='No data loaded') gv.is_test_loaded = False gv.step_button.config(state='disabled') gv.load_model_button.config(state='active') gv.load_test_button.config(state='active') # set images back to original gv.tk_bb_image_1 = PhotoImage(file='../images/bb-3.png') gv.bb_image_left.config(image=gv.tk_bb_image_1) gv.tk_bb_image_2 = PhotoImage(file='../images/bb-2.png') gv.bb_image_right.config(image=gv.tk_bb_image_2) # set step_position back to zero gv.step_position = 0 # set max_position back to zero gv.max_position = 0 gv.certainty_text.config(text='1.00') gv.prediction_text.config(text='Predict: Match', fg='black') gv.truth_text.config(text='Truth: Match', fg='black') gv.reset_button.config(state='disabled') print('reset')
def game(name): """ Quand la boutton est actionné : - Met la case en True - Met les points suivant le joueur (les points permettent de définir le gagnant) - Met la case en croix ou en cercle selon le joueur """ cross = PhotoImage(file='./Image/croix.png') circle = PhotoImage(file='./Image/cercle.png') #Définition du joueur qui joue global player print(player) player += 1 player %= 2 #Pour chaque clef du dictionnaire for nameCase in case.keys(): if str(nameCase) == name: substitute = case[name] if substitute[0] == True: #Si case déjà prise player += 1 player %= 2 #Revient au joueur initial break else: substitute[0] = True #Case prise if player == 0: substitute[1] = 1 #J2 points buttons[substitute[4] - 1].config( image=cross) #Met la croix if player == 1: substitute[1] = 10 #J1 points buttons[substitute[4] - 1].config( image=circle) #Met le cercle case[name] = substitute files()
def __init__(self, parent, controller): Frame.__init__(self, parent) self.parent = parent self.controller = controller self.controller.bindStatic(self) self.battery = True tmpDate = list(localtime()[0:3]) self.curDate = [tmpDate[1], tmpDate[2], int(str(tmpDate[0])[3:])] self.dateTag = None self.curTime = list(localtime()[3:6]) self.timeTag = None self.curAlarm = [ 12, 0, 0] self.alarmTag = None self.curChrono = [ 0, 0, 0] self.chronoTag = None self.noteImage = PhotoImage(file='./noteSmall.gif') self.watchImage = PhotoImage(file='./watch.gif') self.alarmNoteTag = None self.curSelectionInfo = None self.curSelection = ['hours', 'minutes', 'seconds', 'months', 'days', 'years'] self.curSelectionIndex = 0 self.lastPressed = '' self.createWidgets() parent.protocol('WM_DELETE_WINDOW', self.controller.window_close) self.drawTime() self.drawDate() return
def __init__(self): self._root = Tk() self._window_title = 'deepimpression 2.0' self._window_width = 500 self._window_height = 500 + 300 self._window_position = 200 self._camera_image = PhotoImage(file='media/eye.png') self._camera = None self._trait_image_all = PhotoImage(file=trait_image) self._trait_all = None self._run_button = None self._keep_going = False self._model = None self._series_o = [0.5] * series_length self._series_c = [0.5] * series_length self._series_e = [0.5] * series_length self._series_a = [0.5] * series_length self._series_s = [0.5] * series_length self._label_o = None self._label_c = None self._label_e = None self._label_a = None self._label_s = None
def plotting(): """shows plots on interface""" global listbuttons del listbuttons[:] if histograms == []: plots = glob.glob('Output/*.gif') else: plots = [] for i in range(0, len(histograms)): name = imn.ImageDic[histograms[i]] plots.append(glob.glob('Output/' + name + '.gif')) plots = sum(plots, []) expLabel.place_forget() try: for j in range(0, 6): for i in range(0, 4): photo = PhotoImage(file=plots[i + j * 4]) listphotosbig.insert(i + j * 4, photo) photo2 = photo.subsample(6) listphotos.insert(i + j * 4, photo2) def showplot(p=i, q=j): """when plot clicked, open a new window with original size""" newwin = Toplevel() topscrollbar = Scrollbar(newwin) topscrollbar.pack(side=RIGHT, fill=Y) topcanvas = Canvas(newwin, width=900, height=900, yscrollcommand=topscrollbar.set, scrollregion=(0, 0, 0, 900)) topcanvas.pack() bigplot = topcanvas.create_image( 451, 451, image=listphotosbig[p + q * 4]) topscrollbar.config(command=topcanvas.yview) listcommands.insert(i + j * 4, showplot) listbuttons.insert( i + j * 4, Button(frameOUT, command=listcommands[i + j * 4], compound=BOTTOM, text=plots[i + j * 4][7:][:-4], bg="peach puff", image=listphotos[i + j * 4])) listbuttons[i + j * 4].grid(row=j + 1, column=i + 1) except IndexError: pass jetplots = 4 if plots[1] == 'Output/' + 'b-tag Jet Number' + '.gif': jetplots = 5 for i in range(0, jetplots): listbuttons[i].config(bg="lightsteelblue1") listbuttons[-1].config(bg="azure") if histograms == []: for i in range(0, len(listbuttons)): listbuttons[i].config(bg="light grey")
def eye_image_callback(eye_image_data): print("System time: {0}, Device time {1}, Camera id {2}".format( eye_image_data['system_time_stamp'], eye_image_data['device_time_stamp'], eye_image_data['camera_id'])) image = PhotoImage( data=base64.standard_b64encode(eye_image_data['image_data'])) print("{0} width {1}, height {2}".format(image, image.width(), image.height()))
def draw_one_frame(self, picNbr=0): giflist = [] giflist.append(PhotoImage(file='loadingdot1.gif')) giflist.append(PhotoImage(file='loadingdot2.gif')) giflist.append(PhotoImage(file='loadingdot3.gif')) #picNum = picNbr % (len(giflist)) gif = giflist[picNbr] self.canvas.create_image(gif.width() // 2, gif.height() // 2, image=gif)
def setRoomImage(self): if (Game.currentRoom == None): # if dead, set the skull image Game.img = PhotoImage(file="skull.gif") else: # otherwise grab the image for the current room Game.img = PhotoImage(file=Game.currentRoom.image) # display the image on the left of the GUI Game.image.config(image=Game.img) Game.image.image = Game.img
def constructWindow(self): self.frm_home = Tk() self.frm_home.geometry('300x370+0+0') self.frm_home.title('Welcome') self.frm_home.resizable(False, False) Label(self.frm_home, text="Your Bank Name", font=("Courier", 20)).pack() Label(self.frm_home, text="------------------", font=("Courier", 20)).pack() # Label(self.frm_home, text="Enter Account #", font=("Courier", 15)).pack() self.txt_accountNumber = Entry(self.frm_home, justify='center', font=("Courier", 15)) self.txt_accountNumber.pack(fill=X, padx=30) # self.img_begin = PhotoImage(file="img_begin.gif") self.btn_begin = Button(self.frm_home, text="Begin Transaction", font=("Courier", 10), bg='#FFFFFF', image=self.img_begin, compound='left', command=lambda: self.onBeginTransaction()) self.btn_begin.pack(fill=X, padx=10, pady=5) # Label(self.frm_home, text="------- OR -------", font=("Courier", 20)).pack() # self.img_create = PhotoImage(file="img_add_account.gif") self.btn_create = Button(self.frm_home, text="Create Account", anchor='w', font=("Courier", 10), bg='#FFFFFF', image=self.img_create, compound='left', command=lambda: self.onCreate()) self.btn_create.pack(fill=X, padx=10, pady=5) # self.img_exit = PhotoImage(file="img_exit.gif") self.btn_exit = Button(self.frm_home, text="Exit", anchor='w', font=("Courier", 10), bg='#FFFFFF', image=self.img_exit, compound='left', command=lambda: self.onExit()) self.btn_exit.pack(fill=X, padx=10, pady=5) self.frm_home.mainloop() pass # end
def DrawImage(self): pathToFile = "Assets/" + self.color + "_solider" if (self.isKing): pathToFile = pathToFile + "_king" pathToFile = pathToFile + ".gif" self.photo = PhotoImage(file=pathToFile) self.soliderButton = Button(self.master, image=self.photo, background="white", command=lambda: self.onClick(self)) self.soliderButton.grid(row=self.position.Row, column=self.position.Column)
def __init__(self, parent): self.imagen_fondo = PhotoImage(file="Jungle_small_2.gif") self.imagen_choza = PhotoImage(file="Hut_small_2.gif") self.ancho_choza = 60 self.alto_choza = 140 self.container = parent self.Chozas = [] self.result = "" self.ocupar_chozas() self.setup()
def __init__(self): self.root = Tk() self.root.title("Ray Tracer") canvas = Canvas(self.root, width=WIN_SIZE, height=WIN_SIZE) self.image = PhotoImage(master=self.root, width=WIN_SIZE, height=WIN_SIZE) imageCentre = (WIN_SIZE / 2 + 2, WIN_SIZE / 2 + 2) canvas.create_image(imageCentre, image=self.image) canvas.pack() # Enqueue a callback to the ray tracer to start it going self.root.after(0, lambda: self.trace()) return
def updateButtons(self): self.pic1 = PhotoImage(file="1.gif").subsample(6, 6) self.pic2 = PhotoImage(file="2.gif").subsample(6, 6) self.pic3 = PhotoImage(file="3.gif").subsample(6, 6) for r in range(envVar.gridSize): for c in range(envVar.gridSize): if envVar.gridOriginal[r][c] == 0: self.buttons[envVar.gridSize * r + c].config(image=self.pic1) elif envVar.gridOriginal[r][c] == 1: self.buttons[envVar.gridSize * r + c].config(image=self.pic2) elif envVar.gridOriginal[r][c] == 2: self.buttons[envVar.gridSize * r + c].config(image=self.pic3)
def gridd(): """ Crée la grille avec l'interface tkinter et crée les boutons """ global window global intermediateVariable global player window.geometry("680x680") #Dimension de l'interface #default = PhotoImage(file='./Image/default.png') #Boutons: #Le x=0 est le bord gauche de la fenetre #Le y=0 est le bord haut de la fenetre #La position est la position du coin en haut à gauche du bouton # Création des boutons intermediateVariable = 0 cross = PhotoImage(file='./Image/croix.png') for nameCase in case.keys(): newbutton = Button(window, image=cross, name=str(nameCase).lower(), state="active") #Définition du bouton buttons.append(newbutton) #Ajouter à la liste #newbutton.config(command= intermediateFunction(nameCase)) #Commande du bouton substitute = case[nameCase] newbutton.place(x=substitute[2], y=substitute[3]) #Placement du bouton
def stat_image(): img = PhotoImage( format="gif", data= "R0lGODlhEAAQAOYAAAAAAP///5dxdJNtdI9qdItncl6Atnef33uk5Fx+s3uk44Cp6Iav7Yav64Wt" + "6Yew64uz7oq18Yy384659JC79Y638ZC785S+9ZO99JbA9qjP+qvS+maRMGCILV6FLJLAQZG+QpK/" + "SJbEPpXDP5PBQJDEII3BH4q+H5PHIYy/I47CJJLEJZjLKJfHMpjIN6HPPJzKO57MPKTSP6LQPqDP" + "Pp/NPZrIPKXUQZjGPafTTLzlYsjteJfKI5rOJZXHJp7QKJvOKp/QLKPVLqTVMqnZN6nZO6bUPqPR" + "Pa7dQajWQq7cRKnWQ6zYRa3ZSLPgTLPfTrDcTrnjVbTfVLnjV7jhW8fsdMfsdaKOGqSGG6CBHJx8" + "Hph3IJRzIZFvIotsJuaRUuaSUvCMSPGUVPSgZ/Slbt1XBOBdCuBmGuVqG+NrH+d3Lut7Me2FQZcx" + "DZQxDaaAdqWIgqF8dZx2df///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACH5" + "BAEAAHMALAAAAAAQABAAAAe4gHOCg4SFhoU7VVVWTIeEOlFRU0aOg1ROTk9HlYJSSEhKL4MbGhuF" + "UERERTGDGRQZhU1CQkMwgxcTF4VLPz9BNoMYEhhwYF9gV0k9PUA4gxYRFm9kY2RYNzw8LCKDFQwV" + "cWJhYlkyKCg+I4MQCxBybGtsWjMlJSskgw8KDwJqaGpbaJgwoeLDIAcHHAxIYyYNlxonTqQAMagB" + "ggYEzpQ50yVHixYuQgwykMBAgTZu2njp4KElhzmBAAA7") return img
def run(self): print "Creating animation server..." if os.path.exists(SOCKET_NAME): os.remove(SOCKET_NAME) self.server = Animator(AnimationRequestHandler, self.simulate) if not self.simulate: print "Starting animation server..." print "Animation server is running on socket {0}".format( SOCKET_NAME) #print "Quit the server with CONTROL-C." self.server.serve_forever() else: print "Starting simulation..." button_window = Toplevel() button_window.title('Button Input') img = PhotoImage(file="easy_button.gif") single_easy_button = Button(button_window, image=img) single_easy_button.pack() single_easy_button.bind( "<Button-1>", lambda e: server.processCommand(ButtonEvent.SINGLEPRESS)) double_easy_button = Button(button_window, text="double tap") double_easy_button.pack() double_easy_button.bind( "<Button-1>", lambda e: server.processCommand(ButtonEvent.DOUBLEPRESS)) mainloop()
def displaySampleFSM(): resizeimage.resizeImage(filename,0.5) img = PhotoImage(file="../graph/sample0.5.png") label1.image = img # keep a reference! samplaCanvas.delete(img) #reset canvas samplaCanvas.create_image(0, 80, anchor='nw',image=img,tags="bg_img")
def display(): window = Tk() canvas = Canvas(window, width=WIDTH, height=HEIGHT, bg="#000000") canvas.pack() img = PhotoImage(width=WIDTH, height=HEIGHT) canvas.create_image((WIDTH/2, HEIGHT/2), image=img, state="normal") data = "" for i in range(HEIGHT): data += '{' + ' '.join(map( convert_color, memory_dump(i*WIDTH, i*WIDTH + WIDTH) )) + '} ' img.put(data[:-1]) mainloop()
def thresholdFilter(self): img = Image.open(self.img_name) new_img = img.filter(ImageFilter.BLUR) aux = mydir +"/temp/"+ self.new_img_name new_img.save(aux) self.image = PhotoImage(file=aux) self.setImage()
def __gui_create(self): self.root=Tk() self.root.title('ClickNEOBUX') w=self.root.winfo_screenwidth()-180 h=self.root.winfo_screenheight()-50 self.root.geometry('180x80+'+str(w)+'+'+str(h)) self.root.resizable(False,False) self.root.protocol('WM_DELETE_WINDOW',self.__gui_exit) try: self.root.call('wm','iconphoto',self.root._w,PhotoImage(file='data/neobux.png')) except Exception: print 'Error loading icon' self.text_btn=StringVar() self.text_btn.set('Start') Button(self.root,textvariable=self.text_btn,command=self.__gui_click_btn).place(x=50,y=10,height=30,width=80) self.text_lb=StringVar() self.text_lb.set('Pausing ...') Label(self.root,textvariable=self.text_lb).place(x=0,y=50,width=180,height=30) #self.root.after(0,self.__check_status) self.root.mainloop() print 'Exit GUI'
def image(pos, file="../../car.gif"): x, y = pos img = PhotoImage(file=file) return _canvas.create_image(x, y, image=Tkinter.PhotoImage(file=file), anchor=Tkinter.NW)
def __init__(self, master, text): self._text = text Frame.__init__(self, master, background=self.BACKGROUND, highlightbackground="red", borderwidth=1, relief=SOLID) Label(self, text=text, background=self.BACKGROUND, foreground=self.FOREGROUND_LABEL).pack(side=LEFT, pady=(self.PADDING[1], self.PADDING[3]), padx=(self.PADDING[0], 0)) self._close_IMG = PhotoImage( data= "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAAN1wAADdcBQiibeAAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoAAAFySURBVDiNpZM9juJAEIU/WxPY/EstQdICEYAQ+A5eX2CjDTgiMRfwzh4BmcAkTgAJiZZFsF7TbvAmeMUKZoKhouqnrqp+9V5bZVnyStgvVQNv94cgCN6EEAsApdQ8DEPzGQ5gVRRul5ae5wW2bbNarUKl1HeAZ3jV5N8LhBCL6XQaSCmdy+WC53lBFEVLgNlsFkgpHYDr9RpEUbQAfjxQMMagtSaOY8bjsTOZTHyAXq/nrNdrRqMRWuvnO1BKzTebzdIYEwwGAyeOY4bDYQ3glpMkSZ4kSaiUmj/s4H4P/X7f73a7td1uh2VZSCnZ7/fZdrt9v+f/QKEKrXWptaZqnuc5xpinhnlQQQjxTQjhnk4n2u02AFWulPqjlPr5oQqtVstvNBpumqa4rsvhcPhdliWdTqeepin1et0tisIHPlYhz3Ns2+Z4PGZZlv264X6z2aydz2eMMfcl/6sALG8TKIrivTLSE/xTFb5m5a/Gy7/xL3CL+6G7+HoOAAAAAElFTkSuQmCC" ) Button(self, highlightthickness=0, borderwidth=0, background=self.BACKGROUND, activebackground=self.BACKGROUND, image=self._close_IMG, command=self.destroy).pack(side=LEFT, pady=(self.PADDING[1], self.PADDING[3]), padx=(self.LABEL_AND_BUTTON_SPACING, self.PADDING[2]))
def _create_photo(self, path, name): """ Creates a photo for use on the button. """ logger.debug("Create photo.\nPath: %r\nName: %r" % (path, name)) return PhotoImage(format='gif', file=path % (name), name=name)
def __init__(self): #global ginlogger #ginlogger = self # Get real screen dimension # TODO: check for secondary display or just expand with mouse range self.OnEvent = self.callbackOnEvent() screen_width = self.window.winfo_screenwidth() screen_height = self.window.winfo_screenheight() self.WIDTH, self.HEIGHT = screen_width, screen_height self.minx = 0 self.miny = 0 self.maxx = self.WIDTH self.maxy = self.HEIGHT # make image for drawing self.canvas = Canvas(self.window, width=self.WIDTH, height=self.HEIGHT, bg="#000000") self.canvas.pack() self.img = PhotoImage(width=self.WIDTH, height=self.HEIGHT) self.canvas.create_image((self.WIDTH/2, self.HEIGHT/2), image=self.img, state="normal") # save state self.lastevent = [] self.xl = [] self.yl = [] self.cl = [] # setup hooks self.hm.KeyDown = self.OnEvent self.hm.MouseAll = self.OnEvent self.hm.HookKeyboard() self.hm.HookMouse()
def append_chords(self, chords=[]): '''pass a [list] of Chords to the Accordion object''' self.update_idletasks() row = 0 width = max([c.winfo_reqwidth() for c in chords]) for c in chords: i = PhotoImage() # blank image to force Label to use pixel size label = Label(self, text=c.title, image=i, compound='center', width=width, bg=self.style['title_bg'], fg=self.style['title_fg'], bd=2, relief='groove') label.grid(row=row, column=0) c.grid(row=row + 1, column=0, sticky='nsew') c.grid_remove() row += 2 label.bind('<Button-1>', lambda e, c=c: self._click_handler(c)) label.bind('<Enter>', lambda e, label=label, i=i: label.config(bg=self.style[ 'highlight'])) label.bind('<Leave>', lambda e, label=label, i=i: label.config(bg=self.style[ 'title_bg']))
def main_loop(gv): ret, frame = cap.read() frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) if constants.face_algo == 'dlib': # frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) f = frame.astype(np.float32) f = np.transpose(f, (2, 0, 1)) f = np.expand_dims(f, 0) elif constants.face_algo == 'haar': f = frame elif constants.face_algo is None: f = frame else: f = None y, bb = predict_frame(f, gv.model) if bb is not None: frame = draw_bb(frame, bb) img1 = Image.fromarray(frame, 'RGB') img2 = ImageTk.PhotoImage(img1) gv.camera_image = img2 gv.camera.config(image=gv.camera_image) gv.series_e = plotting.update_series(gv.series_e, y[0].data[0]) gv.series_a = plotting.update_series(gv.series_a, y[0].data[1]) gv.series_c = plotting.update_series(gv.series_c, y[0].data[2]) gv.series_s = plotting.update_series(gv.series_s, y[0].data[3]) gv.series_o = plotting.update_series(gv.series_o, y[0].data[4]) loc = plotting.make_plot(gv) gv.trait_image_all = PhotoImage(file=loc) gv.trait_all.config(image=gv.trait_image_all)
def initialize_main_panel(self): # Creates a menu. self.root.title("PyKeylogger Control Panel") self.root.config(height=200, width=200) # Overrides the default exit behaviour. self.root.protocol("WM_DELETE_WINDOW", self.close) # Display the version in main window g = Pmw.Group(self.root, tag_pyclass=None) g.pack(fill='both', expand=1, padx=6, pady=6) textlabel = Label(g.interior(), text="PyKeylogger " + str(version.version), font=("Helvetica", 18)) textlabel.pack(padx=2, pady=2, expand='yes', fill='both') # Pretty logo display. photo = PhotoImage(file=os.path.join(get_main_dir(), version.name + "icon_big.gif")) imagelabel = Label(self.root, image=photo, height=160, width=200) imagelabel.photo = photo imagelabel.pack() # Create and pack the MessageBar. self.message_bar = Pmw.MessageBar(self.root, entry_width=50, entry_relief='groove', labelpos='w', label_text='Status:') self.message_bar.pack(fill='x', padx=10, pady=10) self.message_bar.message('state', 'Please explore the menus.') # Create main menu. menu = MainMenu(self.root, self.panelsettings, self)
def render_2d(header, blocks): from Tkinter import Tk, Label, mainloop, PhotoImage # Create a random color map from the set of blocks values colors = {} for unique_item in set(chain.from_iterable(blocks)): if unique_item == 0: colors[0] = (0, 0, 0) else: colors[unique_item] = (randrange(128), randrange(128), randrange(128)) master = Tk() # Build image photo = PhotoImage(width=header["z"], height=header["y"]) #{#ff0000 #ff0000 #ff0000} {#ff0000 #ff0000 #ff0000} {#ff0000 #ff0000 #ff0000} {#ff0000 #ff0000 #ff0000} horizontal_line = " ".join(["{" + " ".join(["#%02x%02x%02x" % tuple(colors[blockId]) for blockId in row]) + "}" for row in blocks]) photo.put(horizontal_line) photo = photo.zoom(4, 4) label = Label(master, image=photo) label.pack() mainloop()
def __init__(self, master, text=None, borderwidth=2, width=0, height=16, interior_padx=0, interior_pady=8, background=None, caption_separation=4, caption_font=None, caption_builder=None, icon_x=5): Frame.__init__(self, master) if background is None: background = self.cget("background") self.configure(background=background) self._is_opened = False self._interior_padx = interior_padx self._interior_pady = interior_pady self._iconOpen = PhotoImage(data="R0lGODlhEAAQAKIAAP///9TQyICAgEBAQAAAAAAAAAAAAAAAACwAAAAAEAAQAAADNhi63BMgyinFAy0HC3Xj2EJoIEOM32WeaSeeqFK+say+2azUi+5ttx/QJeQIjshkcsBsOp/MBAA7") self._iconClose = PhotoImage(data="R0lGODlhEAAQAKIAAP///9TQyICAgEBAQAAAAAAAAAAAAAAAACwAAAAAEAAQAAADMxi63BMgyinFAy0HC3XjmLeA4ngpRKoSZoeuDLmo38mwtVvKu93rIo5gSCwWB8ikcolMAAA7") height_of_icon = max(self._iconOpen.height(), self._iconClose.height()) width_of_icon = max(self._iconOpen.width(), self._iconClose.width()) containerFrame_pady = (height_of_icon//2) +1 self._height = height self._width = width self._containerFrame = Frame(self, borderwidth=borderwidth, width=width, height=height, relief=RIDGE, background=background) self._containerFrame.pack(expand=True, fill=X, pady=(containerFrame_pady,0)) self.interior = Frame(self._containerFrame, background=background) self._collapseButton = Label(self, borderwidth=0, image=self._iconOpen, relief=RAISED) self._collapseButton.place(in_= self._containerFrame, x=icon_x, y=-(height_of_icon//2), anchor=N+W, bordermode="ignore") self._collapseButton.bind("<Button-1>", lambda event: self.toggle()) if caption_builder is None: self._captionLabel = Label(self, anchor=W, borderwidth=1, text=text) if caption_font is not None: self._captionLabel.configure(font=caption_font) else: self._captionLabel = caption_builder(self) if not isinstance(self._captionLabel, Widget): raise Exception("'caption_builder' doesn't return a tkinter widget") self.after(0, lambda: self._place_caption(caption_separation, icon_x, width_of_icon))
def __init__(self): self.root = Tk() self.root.title("Ray Tracer") canvas = Canvas(self.root, width=WIN_SIZE , height=WIN_SIZE ) self.image = PhotoImage(master=self.root, width=WIN_SIZE, height=WIN_SIZE) imageCentre = (WIN_SIZE / 2 + 2, WIN_SIZE / 2 + 2) canvas.create_image(imageCentre, image = self.image) canvas.pack() # Enqueue a callback to the ray tracer to start it going self.root.after(0, lambda : self.trace() ) return
def __init__(self, update, fps=8): self.t = 0 self.period = 1000/fps self.update = update self.master = Tk() m = self.update(self.t) self.W, self.H = m3d.shape(m) self.img = PhotoImage(width=self.W, height=self.H) canvas = Canvas(self.master, width=self.W, height=self.H) canvas.pack() canvas.create_image((self.W/2, self.H/2), image=self.img, state="normal") self._on_tick()
def openImage(self): arquivo = tkFileDialog.askopenfile(parent=self.canvas,mode='rb', title='Imagem') e = ['GIF','JPEG','JPG','BMP','PNG','TIF'] if(e.__contains__(arquivo.name.split(".")[-1].upper())): self.ponto1, self.ponto2 = (None,None) img_tmp = Image.open(arquivo) #self.img_name = path.dirname(path.abspath(arquivo.name)) self.img_name = arquivo.name print self.img_name self.new_img_name = arquivo.name.split('/')[-1] + "_tmp.gif" pathtemp = mydir +"/temp/"+ self.new_img_name img_tmp.save(pathtemp) self.image = PhotoImage(file=pathtemp) self.setImage() self.canvas.bind("<Button-1>", self.click) self.proporcao = ""
class AppAnalysis: def __init__(self, root): self.canvas = Canvas(root, width = 400, height = 350) self.canvas.configure(cursor="crosshair") self.canvas.pack(expand=YES, fill=BOTH, side='right') self.canvas.bind("<Key>", self.handle_key) self.canvas.bind("<Double-Button-1>", self.set_focus) self.canvas.bind("<Button-1>", self.set_cursor) self.canvas.bind("<Return>", self.remove_highlight) self.image, self.ponto1, self.ponto2 = (None, None, None) self.menubar = Menu(root) filemenu = Menu(self.menubar, tearoff=0) filemenu.add_command(label="Open Image", command=self.openImage) filemenu.add_command(label="Save", command=self.hello) filemenu.add_separator() filemenu.add_command(label="Exit", command=root.quit) self.menubar.add_cascade(label="File", menu=filemenu) editmenu = Menu(self.menubar, tearoff=0) for e in ("Cut","Copy","Paste"): editmenu.add_command(label=e, command=self.hello) self.menubar.add_cascade(label="Edit", menu=editmenu) filtermenu = Menu(self.menubar, tearoff=0) filtermenu.add_command(label="Threshold", command=self.thresholdFilter) self.menubar.add_cascade(label="Filter", menu=filtermenu) reportmenu = Menu(self.menubar, tearoff=0) reportmenu.add_command(label="Relatorio.txt", command=self.generateReport) reportmenu.add_command(label="Relatorio.pdf") reportmenu.add_command(label="Email") self.menubar.add_cascade(label="Report", menu=reportmenu) helpmenu = Menu(self.menubar, tearoff=0) helpmenu.add_command(label="About", command=self.hello) self.menubar.add_cascade(label="Help", menu=helpmenu) root.config(menu=self.menubar) self.toolbar = Frame(root) self.toolbar.pack(side='left', fill='both') clean = Label(self.toolbar, text='Clean') clean.bind("<Button-1>", self.clean) b = Label(self.toolbar, text='B') c = Label(self.toolbar, text='C') d = Label(self.toolbar, text='D') for w in (clean,b,c,d): w.configure(relief="groove", font="Times 12 bold") w.pack(fill='both') def openImage(self): arquivo = tkFileDialog.askopenfile(parent=self.canvas,mode='rb', title='Imagem') e = ['GIF','JPEG','JPG','BMP','PNG','TIF'] if(e.__contains__(arquivo.name.split(".")[-1].upper())): self.ponto1, self.ponto2 = (None,None) img_tmp = Image.open(arquivo) #self.img_name = path.dirname(path.abspath(arquivo.name)) self.img_name = arquivo.name print self.img_name self.new_img_name = arquivo.name.split('/')[-1] + "_tmp.gif" pathtemp = mydir +"/temp/"+ self.new_img_name img_tmp.save(pathtemp) self.image = PhotoImage(file=pathtemp) self.setImage() self.canvas.bind("<Button-1>", self.click) self.proporcao = "" def clean(self, event): self.ponto1, self.ponto2 = (None,None) self.setImage() self.proporcao = "" def setImage(self): self.canvas.delete(ALL) if self.image.width() > 200 and self.image.height > 200: self.canvas.config(width = self.image.width()) self.canvas.config(height = self.image.height()) self.canvas.create_image(0, 0, image=self.image, anchor=NW) def generateReport(self): report = GeradorRelatorio(self.img_name) report.start() def hello(self): print "hello!" def thresholdFilter(self): img = Image.open(self.img_name) new_img = img.filter(ImageFilter.BLUR) aux = mydir +"/temp/"+ self.new_img_name new_img.save(aux) self.image = PhotoImage(file=aux) self.setImage() def click(self, event): if not self.ponto1: self.canvas.create_oval(event.x, event.y, event.x+5, event.y+5, fill="red") self.ponto1 = (event.x,event.y) else: if not self.ponto2: self.canvas.create_oval(event.x, self.ponto1[1], event.x+5, self.ponto1[1]+5, fill="red") self.ponto2 = (event.x,self.ponto1[1]) pontos = [self.ponto1[0]+1,self.ponto1[1]+2, self.ponto2[0]+1,self.ponto2[1]+2] self.canvas.create_line(pontos, tags="theline", fill='red') x = (self.ponto2[0] + self.ponto1[0]) / 2 self.canvas.create_text(x, self.ponto1[1]+8, text="1 umm") def remove_highlight(self,event): self.canvas.delete("highlight") def highlight(self, item): bbox = self.canvas.bbox(item) self.canvas.delete("highlight") if bbox: i = self.canvas.create_rectangle( bbox, fill="white", tag="highlight" ) self.canvas.lower(i, item) def has_focus(self): return self.canvas.focus() def has_selection(self): return self.canvas.tk.call(self.canvas._w, 'select', 'item') def set_focus(self, event): if self.canvas.type(CURRENT) != "text": return self.highlight(CURRENT) self.canvas.focus_set() self.canvas.focus(CURRENT) self.canvas.select_from(CURRENT, 0) self.canvas.select_to(CURRENT, END) def set_cursor(self, event): item = self.has_focus() if not item: return x = self.canvas.canvasx(event.x) y = self.canvas.canvasy(event.y) self.canvas.icursor(item, "@%d,%d" % (x, y)) self.canvas.select_clear() def handle_key(self, event): item = self.has_focus() if not item: return insert = self.canvas.index(item, INSERT) if event.char >= " ": if self.has_selection(): self.canvas.dchars(item, SEL_FIRST, SEL_LAST) self.canvas.select_clear() self.canvas.insert(item, "insert", event.char) self.highlight(item) elif event.keysym == "BackSpace": if self.has_selection(): self.canvas.dchars(item, SEL_FIRST, SEL_LAST) self.canvas.select_clear() else: if insert > 0: self.canvas.dchars(item, insert-1, insert) self.highlight(item) elif event.keysym == "Home": self.canvas.icursor(item, 0) self.canvas.select_clear() elif event.keysym == "End": self.canvas.icursor(item, END) self.canvas.select_clear() elif event.keysym == "Right": self.canvas.icursor(item, insert+1) self.canvas.select_clear() elif event.keysym == "Left": self.canvas.icursor(item, insert-1) self.canvas.select_clear() else: pass
class InputLogger(): #TODO: implement bedder synch because events start missing after some time lock = threading.Lock() f = open("log.txt",'w') window = Tk() hm = pyHook.HookManager() #TODO check for secondary display def __init__(self): #global ginlogger #ginlogger = self # Get real screen dimension # TODO: check for secondary display or just expand with mouse range self.OnEvent = self.callbackOnEvent() screen_width = self.window.winfo_screenwidth() screen_height = self.window.winfo_screenheight() self.WIDTH, self.HEIGHT = screen_width, screen_height self.minx = 0 self.miny = 0 self.maxx = self.WIDTH self.maxy = self.HEIGHT # make image for drawing self.canvas = Canvas(self.window, width=self.WIDTH, height=self.HEIGHT, bg="#000000") self.canvas.pack() self.img = PhotoImage(width=self.WIDTH, height=self.HEIGHT) self.canvas.create_image((self.WIDTH/2, self.HEIGHT/2), image=self.img, state="normal") # save state self.lastevent = [] self.xl = [] self.yl = [] self.cl = [] # setup hooks self.hm.KeyDown = self.OnEvent self.hm.MouseAll = self.OnEvent self.hm.HookKeyboard() self.hm.HookMouse() # this is the event callback for the windows pyhook def callbackOnEvent(self): self.n = 0 def OnEvent(event): self.lastevent t1 = int(round(time.time()*1000)) #log only new entries to file currentevent = [i for i in event.__dict__.items() if "__" not in i[0]] # convert class to list of attributes-names and values onlynew = [i for i in currentevent if i not in self.lastevent] # only print changed attributes print t1, currentevent# onlynew self.f.write(str(t1)+ str(currentevent)+"\n") self.lastevent = currentevent # save position in instance if 'Position' in [k for k,v in currentevent]: #self.lock.acquire() self.xl.append(event.Position[0]) self.yl.append(event.Position[1]) self.cl.append(self.n) self.n+=1 #print self.xl[-1] , self.yl[-1] #self.lock.release() return True return OnEvent def loop(self): # TODO: split logging and display tasks !!!!!!!! updatetime = time.time() updatetimefile = time.time() while 1: pythoncom.PumpWaitingMessages() if len(self.xl): #self.img.blank() self.img.put("#ff0000", (self.WIDTH/2, self.HEIGHT/2)) commonlen = zip(self.xl,self.yl,self.cl) for x,y,c in commonlen: self.img.put("#ffffff", (abs(x),abs(y))) # find extrema for x and y if x < self.minx: self.minx = x elif x > self.maxx: self.maxx = x if y < self.miny: self.miny = y elif y > self.maxy: self.maxy = y #print c, x, y # "del positions" #self.lock.acquire() del self.xl[:len(commonlen)] del self.yl[:len(commonlen)] del self.cl[:len(commonlen)] #self.lock.release() if time.time() > updatetime: self.window.update() updatetime = time.time() + 1/60.
def initialize(self): ################ Menu ################ self.menu1 = Tkinter.Menu(tearoff=0) self.fichier = Tkinter.Menu(tearoff=0) self.menu1.add_cascade(label="Fichier", menu=self.fichier) self.fichier.add_command(label=" Quitter", command=self.quitter) self.fichier = Tkinter.Menu(tearoff=0) self.menu1.add_cascade(label="Aide", menu=self.fichier) self.fichier.add_command(label=" A propos", command=self.apropos) self.config(menu=self.menu1) ################ /Menu ############### self.grid() """ ## champ IP ## self.labelIP = Tkinter.Label(self,anchor='w',text="IP du serveur Qemu :") self.labelIP.grid(column=0,row=0,sticky='EW') self.entryVariableIP = Tkinter.StringVar() self.entryVariableIP.set("Not supported yet") self.entryIP = Tkinter.Entry(self,textvariable=self.entryVariableIP) self.entryIP.grid(column=0,row=1,sticky='EW') """ ## champ Port LED verte ## self.labelPortVerte = Tkinter.Label(self, anchor="w", text="Port LED verte :") self.labelPortVerte.grid(column=0, row=2, sticky="EW") self.entryVariablePortVerte = Tkinter.StringVar() self.entryVariablePortVerte.set(u"4242") self.entryPortVerte = Tkinter.Entry(self, textvariable=self.entryVariablePortVerte) self.entryPortVerte.grid(column=0, row=3, sticky="EW") ## champ Port LED Bleue ## self.labelPortBleue = Tkinter.Label(self, anchor="w", text="Port LED bleue :") self.labelPortBleue.grid(column=0, row=4, sticky="EW") self.entryVariablePortBleue = Tkinter.StringVar() self.entryVariablePortBleue.set(u"4243") self.entryPortBleue = Tkinter.Entry(self, textvariable=self.entryVariablePortBleue) self.entryPortBleue.grid(column=0, row=5, sticky="EW") ## champ Port Bouton ## self.labelPortBouton = Tkinter.Label(self, anchor="w", text="Port Bouton :") self.labelPortBouton.grid(column=0, row=6, sticky="EW") self.entryVariablePortBouton = Tkinter.StringVar() self.entryVariablePortBouton.set(u"4244") self.entryPortBouton = Tkinter.Entry(self, textvariable=self.entryVariablePortBouton) self.entryPortBouton.grid(column=0, row=7, sticky="EW") button = Tkinter.Button(self, text="Lancer", command=self.OnButtonLancerClick) button.grid(column=0, row=8, sticky="EW") self.labelLog = Tkinter.Label(self, anchor="w", text="Log : ") self.labelLog.grid(column=0, row=9, sticky="EW") self.log = Tkinter.Text(width=20, height=20) self.log.grid(column=0, row=10, sticky="EWNS", rowspan=50) self.log.insert(Tkinter.END, "") button2 = Tkinter.Button(self, text="Vider", command=self.Clear) button2.grid(column=0, row=60, sticky="EW") scrollbar = Tkinter.Scrollbar(self.log, width=10) scrollbar.pack(side="right", fill="y") scrollbar.config(command=self.log.yview) self.log.config(yscrollcommand=scrollbar.set) # Images # self.carte = PhotoImage(file="img/carte.gif") self.ledBlanche = PhotoImage(file="img/LEDblanche.gif") self.ledBleue = PhotoImage(file="img/LEDbleue.gif") self.ledVerte = PhotoImage(file="img/LEDverte.gif") self.user = PhotoImage(file="img/user.gif") self.canvas = Tkinter.Canvas(self, width=self.carte.width(), height=self.carte.height()) self.canvas.grid(column=2, row=1, rowspan=70) self.canvas.create_image(0, 0, anchor="nw", image=self.carte) self.canvas.create_image(70, 390, image=self.user, tag="user", anchor="nw") self.canvas.create_image(150, 390, image=self.user, tag="reset", anchor="nw") self.canvas.tag_bind("reset", "<B1-ButtonRelease>", self.Reset) self.canvas.tag_bind("user", "<Button-1>", self.UserPressed) self.canvas.tag_bind("user", "<B1-ButtonRelease>", self.UserReleased) self.ledGauche = self.canvas.create_image(35, 400, anchor="nw", image=self.ledBlanche) self.ledDroite = self.canvas.create_image(190, 400, anchor="nw", image=self.ledBlanche) # self.grid_columnconfigure(1,weight=1) # self.grid_columnconfigure(0,weight=1) INUTILE # self.grid_rowconfigure(0,weight=1) #Gestion verticale de l'agrandissement self.resizable(False, False) # Pas redimentionable ! # self.geometry(self.geometry()) self.update()
class CollapsibleFrame(Frame): def __init__(self, master, text=None, borderwidth=2, width=0, height=16, interior_padx=0, interior_pady=8, background=None, caption_separation=4, caption_font=None, caption_builder=None, icon_x=5): Frame.__init__(self, master) if background is None: background = self.cget("background") self.configure(background=background) self._is_opened = False self._interior_padx = interior_padx self._interior_pady = interior_pady self._iconOpen = PhotoImage(data="R0lGODlhEAAQAKIAAP///9TQyICAgEBAQAAAAAAAAAAAAAAAACwAAAAAEAAQAAADNhi63BMgyinFAy0HC3Xj2EJoIEOM32WeaSeeqFK+say+2azUi+5ttx/QJeQIjshkcsBsOp/MBAA7") self._iconClose = PhotoImage(data="R0lGODlhEAAQAKIAAP///9TQyICAgEBAQAAAAAAAAAAAAAAAACwAAAAAEAAQAAADMxi63BMgyinFAy0HC3XjmLeA4ngpRKoSZoeuDLmo38mwtVvKu93rIo5gSCwWB8ikcolMAAA7") height_of_icon = max(self._iconOpen.height(), self._iconClose.height()) width_of_icon = max(self._iconOpen.width(), self._iconClose.width()) containerFrame_pady = (height_of_icon//2) +1 self._height = height self._width = width self._containerFrame = Frame(self, borderwidth=borderwidth, width=width, height=height, relief=RIDGE, background=background) self._containerFrame.pack(expand=True, fill=X, pady=(containerFrame_pady,0)) self.interior = Frame(self._containerFrame, background=background) self._collapseButton = Label(self, borderwidth=0, image=self._iconOpen, relief=RAISED) self._collapseButton.place(in_= self._containerFrame, x=icon_x, y=-(height_of_icon//2), anchor=N+W, bordermode="ignore") self._collapseButton.bind("<Button-1>", lambda event: self.toggle()) if caption_builder is None: self._captionLabel = Label(self, anchor=W, borderwidth=1, text=text) if caption_font is not None: self._captionLabel.configure(font=caption_font) else: self._captionLabel = caption_builder(self) if not isinstance(self._captionLabel, Widget): raise Exception("'caption_builder' doesn't return a tkinter widget") self.after(0, lambda: self._place_caption(caption_separation, icon_x, width_of_icon)) def update_width(self, width=None): # Update could be devil # http://wiki.tcl.tk/1255 self.after(0, lambda width=width:self._update_width(width)) def _place_caption(self, caption_separation, icon_x, width_of_icon): self.update() x = caption_separation + icon_x + width_of_icon y = -(self._captionLabel.winfo_reqheight()//2) self._captionLabel.place(in_= self._containerFrame, x=x, y=y, anchor=N+W, bordermode="ignore") def _update_width(self, width): self.update() if width is None: width=self.interior.winfo_reqwidth() if isinstance(self._interior_pady, (list, tuple)): width += self._interior_pady[0] + self._interior_pady[1] else: width += 2*self._interior_pady width = max(self._width, width) self._containerFrame.configure(width=width) def open(self): self._collapseButton.configure(image=self._iconClose) self._containerFrame.configure(height=self.interior.winfo_reqheight()) self.interior.pack(expand=True, fill=X, padx=self._interior_padx, pady =self._interior_pady) self._is_opened = True def close(self): self.interior.pack_forget() self._containerFrame.configure(height=self._height) self._collapseButton.configure(image=self._iconOpen) self._is_opened = False def toggle(self): if self._is_opened: self.close() else: self.open()
class UI(Tkinter.Tk): def __init__(self,parent): Tkinter.Tk.__init__(self,parent) self.parent = parent self.initialize() def initialize(self): ################ Menu ################ self.menu1 = Tkinter.Menu(tearoff=0) self.fichier = Tkinter.Menu(tearoff=0) self.menu1.add_cascade(label="File",menu=self.fichier) self.fichier.add_command(label=" Quit", command=self.quitter) self.fichier = Tkinter.Menu(tearoff=0) self.menu1.add_cascade(label="About",menu=self.fichier) self.fichier.add_command(label=" A propos", command=self.apropos) self.config(menu=self.menu1) ################ /Menu ############### self.grid() ''' ## champ IP ## self.labelIP = Tkinter.Label(self,anchor='w',text="IP du serveur Qemu :") self.labelIP.grid(column=0,row=0,sticky='EW') self.entryVariableIP = Tkinter.StringVar() self.entryVariableIP.set("Not supported yet") self.entryIP = Tkinter.Entry(self,textvariable=self.entryVariableIP) self.entryIP.grid(column=0,row=1,sticky='EW') ''' ## champ Port LED green ## self.labelPortVerte = Tkinter.Label(self,anchor='w',text="Port of LED Green :") self.labelPortVerte.grid(column=0,row=2,sticky='EW') self.entryVariablePortVerte = Tkinter.StringVar() self.entryVariablePortVerte.set(u"4242") self.entryPortVerte = Tkinter.Entry(self,textvariable=self.entryVariablePortVerte) self.entryPortVerte.grid(column=0,row=3,sticky='EW') ## champ Port LED Bleue ## self.labelPortBleue = Tkinter.Label(self,anchor='w',text="Port of LED Blue :") self.labelPortBleue.grid(column=0,row=4,sticky='EW') self.entryVariablePortBleue = Tkinter.StringVar() self.entryVariablePortBleue.set(u"4243") self.entryPortBleue = Tkinter.Entry(self,textvariable=self.entryVariablePortBleue) self.entryPortBleue.grid(column=0,row=5,sticky='EW') ## champ Port Bouton ## self.labelPortBouton = Tkinter.Label(self,anchor='w',text="Port of Bouton :") self.labelPortBouton.grid(column=0,row=6,sticky='EW') self.entryVariablePortBouton = Tkinter.StringVar() self.entryVariablePortBouton.set(u"4244") self.entryPortBouton = Tkinter.Entry(self,textvariable=self.entryVariablePortBouton) self.entryPortBouton.grid(column=0,row=7,sticky='EW') button = Tkinter.Button(self,text="Launch",command=self.OnButtonLancerClick) button.grid(column=0,row=8,sticky="EW") self.labelLog = Tkinter.Label(self,anchor='w',text="Log : ") self.labelLog.grid(column=0,row=9,sticky='EW') self.log = Tkinter.Text(width=20,height=20) self.log.grid(column=0,row=10,sticky='EWNS',rowspan=50) self.log.insert(Tkinter.END,"") button2 = Tkinter.Button(self,text="Clear",command=self.Clear) button2.grid(column=0,row=60,sticky="EW") scrollbar = Tkinter.Scrollbar(self.log,width=10) scrollbar.pack(side='right', fill='y') scrollbar.config(command=self.log.yview) self.log.config(yscrollcommand=scrollbar.set) # Images # self.carte=PhotoImage(file="img/carte.gif") self.ledBlanche=PhotoImage(file="img/LEDblanche.gif") self.ledBleue=PhotoImage(file="img/LEDblue.gif") self.ledVerte=PhotoImage(file="img/LEDgreen.gif") self.user=PhotoImage(file="img/user.gif") self.canvas = Tkinter.Canvas(self,width=self.carte.width(),height=self.carte.height()) self.canvas.grid(column=2,row=1,rowspan=70) self.canvas.create_image(0,0, anchor = "nw", image=self.carte) self.canvas.create_image(70,390,image=self.user, tag="user", anchor = "nw") self.canvas.create_image(150,390,image=self.user, tag="reset", anchor = "nw") self.canvas.tag_bind("reset", "<B1-ButtonRelease>",self.Reset) self.canvas.tag_bind("user", "<Button-1>",self.UserPressed) self.canvas.tag_bind("user", "<B1-ButtonRelease>",self.UserReleased) self.ledGauche = self.canvas.create_image(35,400, anchor = "nw", image=self.ledBlanche) self.ledDroite = self.canvas.create_image(190,400, anchor = "nw", image=self.ledBlanche) #self.grid_columnconfigure(1,weight=1) #self.grid_columnconfigure(0,weight=1) INUTILE #self.grid_rowconfigure(0,weight=1) #Gestion verticale de l'agrandissement self.resizable(False,False) #Pas redimentionable ! #self.geometry(self.geometry()) self.update() def OnButtonLancerClick(self): app.event.set() def UserPressed(self,none): self.log.insert(Tkinter.END,"User button pressed\n") app.user_pressed() self.log.see(Tkinter.END) def UserReleased(self,none): self.log.insert(Tkinter.END,"User button released\n") app.user_released() self.log.see(Tkinter.END) def Reset(self,none): self.log.insert(Tkinter.END,"Reset button clicked\n") self.log.see(Tkinter.END) def Clear (self): self.log.delete(1.0, Tkinter.END) def quitter(self): if hasattr(app,'thread') : app.close_conn() self.quit() def printlog(self, m): self.labelVariableLog.set(m) self.update() def apropos(self): self.apropos = Fenetre()
return None return pt + ray * solution print ray_sphere_hit_point(Vector(0,0,0), Vector(1,0,0), Vector(2,1,0), 1) from Tkinter import Tk, Canvas, PhotoImage, mainloop w = 400 h = 300 win = Tk() can = Canvas(win, width=w, height=h, bg="#000000") can.pack() img = PhotoImage(width=w, height=h) can.create_image((w/2, h/2), image=img, state="normal") pt = Vector(0,0,0) sphere_center = Vector(100, 0, 0) sphere_radius = 70 max_dist = 100 def color(dist): r = 255 - int( min(dist, max_dist) / float(max_dist) * 255.0) return '#' + (hex(r)[2:] * 3) for y in range(0, w): for z in range(0, h): sln = intersect_ray_sphere(pt, Vector(100, y - w/2, z - h/2),
class rayCaster(object): def __init__(self): self.root = Tk() self.root.title("Ray Tracer") canvas = Canvas(self.root, width=WIN_SIZE , height=WIN_SIZE ) self.image = PhotoImage(master=self.root, width=WIN_SIZE, height=WIN_SIZE) imageCentre = (WIN_SIZE / 2 + 2, WIN_SIZE / 2 + 2) canvas.create_image(imageCentre, image = self.image) canvas.pack() # Enqueue a callback to the ray tracer to start it going self.root.after(0, lambda : self.trace() ) return def putImageRow(self, row, colours): """Output a list of colours to the specified row of the image. Tk uses horrible hexadecimal formatted colours, packed into a string separated by spaces and all enclosed in braces." """ hexColours = ["#%02x%02x%02x" % colour for colour in colours] rowColourString = "{" + " ".join(hexColours) + "}" self.image.put(rowColourString, to=(0, row)) self.root.update() # Main body. Set up an image then compute colour at each pixel def trace(self): camera = definition.camera camera.img = Image.new("RGB", (camera.size, camera.size)) print "ScottTracer" print "\tTracing Rays... 0%", sys.stdout.flush() count = 0 t0 = time.clock() max = float(WIN_SIZE**2) lastPercentage = 0 for row in range(WIN_SIZE): ROW = [] for col in range(WIN_SIZE): count += 1 pixel = camera.pixelColour(col, row) camera.img.putpixel((col, row), pixel.intColour()) ROW.append(pixel.intColour()) percentage = (count / max * 100) self.putImageRow(row, ROW) if percentage - lastPercentage > .9: print "\b\b\b\b\b\b%4.0f%%" % percentage, sys.stdout.flush() lastPercentage = percentage print "\b\b\b\b\b\b Done (%f sec)" % (time.clock() - t0) print "\tAnti-alasing... 0%", sys.stdout.flush() t0 = time.clock() count = 0 lastPercentage = 0 for row in range(WIN_SIZE): ROW = [] self.putImageRow(row, [(255,255,255)] * WIN_SIZE) for col in range(WIN_SIZE): count += 1 pixel = camera.aa(col, row) camera.img.putpixel((col, row), pixel) ROW.append(pixel) percentage = (count / max * 100) self.putImageRow(row, ROW) if percentage - lastPercentage > .9: print "\b\b\b\b\b\b%4.0f%%" % percentage, sys.stdout.flush() lastPercentage = percentage print "\b\b\b\b\b\b (%f sec)" % (time.clock() - t0) print camera.pixels camera.img.save(sys.argv[1] + ".png") # Display image in default image-viewer application
def open_file(self, filename): self._img = PhotoImage(file=filename) self.refresh()
def main(): ImageFile.MAXBLOCK = 4096*2304 # this is only required for older PIL versions, if PILs output buffer is not large enough. see: https://mail.python.org/pipermail/image-sig/1999-August/000816.html parser = argparse.ArgumentParser(description='Simple Raytracer by Tilman Ginzel') parser.add_argument('-r', '--recursive', help='sets recursive depth, e.g. -r 3 (required)', nargs=1, type=checkPositiveInt, required=True, metavar='') parser.add_argument('-s', '--size', help='sets the size, e.g. -s 400 400', nargs=2, default=[400, 400], type=checkPositiveInt, required=False, metavar='') parser.add_argument('-v', '--verbose', help='enable live visualization while processing (slower)', required=False, action='store_true') parser.add_argument('-m', '--material', help='enable materials', required=False, action='store_true') parser.add_argument('-a', '--antialiasing', help='enables 4xSSAA (hence, 4 times slower)', required=False, action='store_true') parser.add_argument('-o', '--output', help='saves image to "./saves/"', required=False, action='store_true') parser.add_argument('-set', '--setting', help='choose a setting. -set 1 - 3', required=False, nargs=1, default=[1], type=int, metavar='') parser.add_argument('-nd', '--no-display', help='this should only be set if the script runs on a server without a $DISPLAY environment variable set!', required=False, action='store_true') try: args = vars(parser.parse_args()) except: parser.print_help() sys.exit(1) settingId = args['setting'][0] if settingId == 1: # default setting setting = DefaultSetting(width=args['size'][0], height=args['size'][1], recursiveDepth=args['recursive'][0], showMaterial=args['material']) elif settingId == 2: # space setting setting = SpaceSetting(width=args['size'][0], height=args['size'][1], recursiveDepth=args['recursive'][0], showMaterial=args['material']) elif settingId == 3: # room setting setting = RoomSetting(width=args['size'][0], height=args['size'][1], recursiveDepth=args['recursive'][0], showMaterial=args['material']) else: # default setting setting = DefaultSetting(width=args['size'][0], height=args['size'][1], recursiveDepth=args['recursive'][0], showMaterial=args['material']) # display is used to set whether you want to have a visual feedback in a graphical user interface. display = not args['no_display'] # easier to read and you do not have to negotiate it on every call if display: window = Tk() window._root().wm_title('Raytracer - Tilman Ginzel (173388)') if args['verbose']: can = Canvas(window, width=setting.WIDTH, height=setting.HEIGHT) else: frame = Frame(window, width=setting.WIDTH, height=setting.HEIGHT) can = Canvas(frame, width=setting.WIDTH, height=setting.HEIGHT) frame = Frame(window) can.pack() # photoImage is used to show live changes while processing if args['verbose']: photoImage = PhotoImage(width=setting.WIDTH, height=setting.HEIGHT) can.create_image((setting.WIDTH/2, setting.HEIGHT/2), image=photoImage, state="normal") # pilImage is used to save the image after processing or if verbose is deactivated pilImage = Image.new("RGB", (setting.WIDTH, setting.HEIGHT), (0, 0, 0)) start = time.clock() processor = Processor(setting, display=display, ssaa=args['antialiasing']) print 'start processing...' for pixel in processor.startProcessing(): if display and args['verbose']: photoImage.put("#%02x%02x%02x" %((pixel[1][0], pixel[1][1], pixel[1][2])), (pixel[0][0], pixel[0][1])) if pixel[0][1] == setting.HEIGHT-1: # if y == bottom, update canvas can.update() pilImage.putpixel((pixel[0][0], pixel[0][1]), ((pixel[1][0], pixel[1][1], pixel[1][2]))) end = time.clock() print 'done' print 'duration: %2.2f seconds' %(end-start) if display and not args['verbose']: tkImage = ImageTk.PhotoImage(pilImage) label = Label(image=tkImage) label.image = tkImage label.pack() can.pack() if args['output']: saveImage(pilImage, args) if display: window.mainloop()