def load_pics(self, pic_url): """Determine the next video to be show and return three preview images.""" pic_url = re.search(".+\.(?=([0-9]+.jpg))", pic_url).group() pic_url = pic_url + "{0}.jpg" # make url able to take .format() method url1 = pic_url.format(10) url2 = pic_url.format(20) url3 = pic_url.format(30) count = 0 while count < 2: count += 1 try: r1 = requests.get(url1) r2 = requests.get(url2) r3 = requests.get(url3) r1.close(); r2.close(); r3.close(); pic1 = PhotoImage(Image.open(BytesIO(r1.content))) pic2 = PhotoImage(Image.open(BytesIO(r2.content))) pic3 = PhotoImage(Image.open(BytesIO(r3.content))) return pic1, pic2, pic3 except requests.exceptions.ConnectionError: if count < 2: print("Connection error, waiting...") time.sleep(3) print("Trying again.") else: print("Connection error. Pics not loaded.")
def update_image(self): if self.tkcanvas is None: return cr = self.tkcanvas # remove all old items from the canvas items = cr.find_all() for item in items: cr.delete(item) wd, ht = self.get_window_size() # make a Tk photo image and stick it to the canvas if have_pil_imagetk: # Get surface as a numpy array arr8 = self.get_image_as_array() image = PILimage.fromarray(arr8) photo = PhotoImage(image) else: # fallback to a little slower method--make a PNG image buf = self.get_rgb_image_as_buffer(format='png') image = buf.getvalue() photo = PhotoImage(data=image) # hang on to a reference otherwise it gets gc'd self.tkphoto = photo cr.create_image(0, 0, anchor='nw', image=photo) # is this necessary? cr.config(scrollregion=cr.bbox('all'))
def rightClick(self, pos): x = pos[0] y = pos[1] buttonConfig = {'bd': 7, 'width': 15, 'height': 15, 'text': ' ', 'relief': 'raised', 'font': ['Montserrat', 11, 'bold'], 'compound': 'center'} if self.cellStateGrid[x, y] == Minesweeper.CELL_STATES.UNOPENED: if self.noOfBombsLeft == 0: return self.cellStateGrid[x, y] = Minesweeper.CELL_STATES.FLAGGED self.noOfBombsLeft -= 1 image = PhotoImage(file=os.path.join(self.imagesDirectoryPath, 'flag.png')) buttonConfig['image'] = image buttonConfig['bg'] = '#BEA57D' self.buttonGrid[x][y].image = image if self.noOfBombsLeft < 10: self.rightLabelText.set('0' + str(self.noOfBombsLeft)) else: self.rightLabelText.set(self.noOfBombsLeft) self.buttonGrid[x][y].config(buttonConfig) elif self.cellStateGrid[x, y] == Minesweeper.CELL_STATES.FLAGGED: self.cellStateGrid[x, y] = Minesweeper.CELL_STATES.UNOPENED self.noOfBombsLeft += 1 image = PhotoImage(file=os.path.join(self.imagesDirectoryPath, 'unexplored.png')) buttonConfig['image'] = image buttonConfig['bg'] = '#224908' self.buttonGrid[x][y].image = image if self.noOfBombsLeft < 10: self.rightLabelText.set('0' + str(self.noOfBombsLeft)) else: self.rightLabelText.set(self.noOfBombsLeft) self.buttonGrid[x][y].config(buttonConfig)
def __init__(self, vid, frameCam, ws, hs, x, y): self.frameCam = frameCam self.ws = ws self.hs = hs self.vid = vid self.cam = tkinter.Canvas(self.frameCam, width=((ws - 780) / 4), height=((hs - 100) / 4), bg='gray50') if vid != None: self.update() # self.cam.mainloop() # --tao menu popup--- self.iconShowCam = PhotoImage(file='./icons/showCam.png') self.iconSettingCam = PhotoImage(file='./icons/settingCam.png') self.iconOff = PhotoImage(file='./icons/off-icon.png') self.iconAddCam = PhotoImage(file='./icons/on-addCam.png') menuCam = Menu(self.cam, tearoff=0) menuCam.add_command(label='Add Cam', command=lambda: self.settingApp('Add_Cam'), underline=0, compound='left', image=self.iconAddCam) menuCam.add_command(label='Show', underline=0, command=lambda: self.settingApp('Show'), compound='left', image=self.iconShowCam) menuCam.add_command(label='Nhận diện khuôn mặt', command=lambda :self.settingApp('Nhận diện khuôn mặt'),compound='left', image=self.iconOff , accelerator='Off') menuCam.add_command(label='Đếm số lượng người', command=lambda :self.settingApp('Đếm số lượng người'), compound=LEFT, image=self.iconOff, accelerator='Off') menuCam.add_command(label='Nhận Diện Biển số xe ', command=lambda: self.settingApp('Setting'), underline=0, compound='left', image=self.iconOff, accelerator='Off') menuCam.add_command(label='Destroy Cam', command=lambda: self.settingApp('Destroy_Cam'), underline=0, compound='left', image=self.iconOff) def popup(event): menuCam.post(event.x_root, event.y_root) self.cam.bind('<Button-3>', popup) self.cam.grid(row=x, column=y)
def __init__(self): super(Env, self).__init__() self.time_step = TIMESTEP self.learning_rate = LR self.gamma = GAMMA self.decay = DECAY self.epsilon = EPSILON self.total_episode = TOTAL_EPISODE self.episode = 1 self.total_reward = INITIAL_REWARD self.action_space = ['u', 'd', 'l', 'r'] self.n_actions = len(self.action_space) self.title('Q Learning Simulator --- made by hyuk') self.fontStyle1 = tkFont.Font(family="Lucida Grande", size=20) self.fontStyle2 = tkFont.Font(family="Lucida Grande", size=13) self.fontStyle3 = tkFont.Font(family="Lucida Grande", size=17) self.start_image = PhotoImage( Image.open("img/start.png").resize( (int(UNIT * 1 / 2), int(UNIT * 1 / 2)))) self.bg_image = PhotoImage( Image.open("img/bg3.jpg").resize( (WIDTH * UNIT * 2, HEIGHT * UNIT * 2))) self.geometry('{0}x{1}'.format((WIDTH + 4) * UNIT, max(5, HEIGHT) * UNIT)) self.shapes = self.load_images() self.canvas = self._build_canvas() self.texts = [] self.action_dict = {0: "up", 1: "down", 2: "left", 3: "right"} self.epsilon_changed = False
def _generate_crewman(cls): for i in [1, 2]: cls._pictures[f"crewman{i}"] = PhotoImage( cls._get_raw_image(f"crewman{i}")) crewman_size = cls._get_raw_image("crewman1").size cls._pictures["crewman0"] = PhotoImage( cls._get_raw_image("transparent").resize(crewman_size, ANTIALIAS))
def retrieve_input(self): self.input = self.w.get("1.0", END) self.w.destroy() self.button1.destroy() self.result_frame = Frame(self.f, height=500, width=500, bg='#fdfefe') self.result_frame.place(x=500, y=180) print('result frame') self.button3 = Button(self.result_frame, text="Back", height=1, width=5, bg='#fdfefe', fg='grey', command=self.back) self.button3.place(x=450, y=5) print('button 3rd') self.result = self.generate_result() x = 0 if self.result[0] == 'positive': print('1st') x += 5 print(x) space = 70 file = '4_1.png' text = 'This Review is Positive' elif self.result[0] == 'neutral': x += 3 file = '4_1.png' text = 'This Review is Neutral' space = 150 else: x += 1 file = '4_1.png' text = 'This Review is Negative' space = 200 self.lst = [ PhotoImage(file=file), PhotoImage(file=file), PhotoImage(file=file), PhotoImage(file=file), PhotoImage(file=file) ] for i in range(x): print('loop') logolbl = Label(self.result_frame, image=self.lst[i], bg='white') logolbl.place(x=(i * 70) + space, y=10) Label( self.result_frame, text= f" Status : {text}\nModel Used : RandomForest Classification\n\tAccuracy : 83.70%", font=self.myfont, bg='#fdfefe', fg='#273746').place(x=10, y=300)
def load_images(): rectangle = PhotoImage( Image.open("img/rectangle.png").resize((65, 65))) triangle = PhotoImage( Image.open("img/triangle.png").resize((65, 65))) circle = PhotoImage( Image.open("img/circle.png").resize((65, 65))) return rectangle, triangle, circle
def get_file_frame(master, file_path_var: StringVar): # colors bg = color['surface-dark'] fg = color['high'] files_var = StringVar() parent = Frame(master, bg=bg) recent_files_frame = get_recent_files_frame(parent, file_path_var, files_var, bg) recent_files_frame.pack(expand=True) add_to_recent = use_recent_files_logic(files_var) def on_browse_btn(): file_path = filedialog.askopenfilename(filetypes=valid_file_types) add_to_recent(file_path) file_path_var.set(file_path) def on_create_btn(): file_path = filedialog.asksaveasfilename(filetypes=valid_file_types) add_to_recent(file_path) file_path_var.set(file_path) control_frame = Frame(parent, bg=bg) file_icon = PhotoImage( generate_colored_icon(open_icon('file_tab', (24, 24)), '#FFFFFF')) add_icon = PhotoImage( generate_colored_icon(open_icon('add_icon', (24, 24)), '#FFFFFF')) browse_btn = Button(control_frame, text='Open File', bg=color['accent'], fg=fg, relief=FLAT, image=file_icon, compound='left') browse_btn.image = file_icon create_btn = Button(control_frame, text='Create File', bg=color['accent'], fg=fg, relief=FLAT, image=add_icon, compound='left') create_btn.image = add_icon browse_btn.pack(expand=True, fill='both', side='left', padx=16, pady=16) create_btn.pack(expand=True, fill='both', side='left', padx=16, pady=16) control_frame.pack() browse_btn.configure(command=on_browse_btn) create_btn.configure(command=on_create_btn) return parent
def set_application_icons(application, path): """Sets the application/window icon for all top-level windows. Assumes that the application has two icons in the given path, icon_16x16.gif and icon_32x32.gif. (Does nothing on Mac OS X.) """ icon32 = PhotoImage(file=os.path.join(path, "icon_32x32.gif")) icon16 = PhotoImage(file=os.path.join(path, "icon_16x16.gif")) application.tk.call("wm", "iconphoto", application, "-default", icon32, icon16)
def __fresh(self): URLs = self.__select_box.get(0, self.__select_box.size()) self.__trend_ob = Trend(URLs) cloud_image, top_image = self.__trend_ob.get_img() self.__cloud_image = PhotoImage(cloud_image) self.__cloud_img_label.configure(image=self.__cloud_image) self.__top_image = PhotoImage(top_image) self.__top_img_label.configure(image=self.__top_image)
def parser_gui(username, password): # Working Frame main_frame2 = Frame(root) main_frame2.place(relwidth=1, relheight=1) # Background img = PhotoImage( Image.open(os.path.join(os.getcwd(), r'img\after_login_back.png'))) background = Label(main_frame2, image=img) background.place(relwidth=1, relheight=1) background.image = img # Button img grades_button_img = PhotoImage( Image.open(os.path.join(os.getcwd(), r'img\Grades_button.png'))) gpa_button_img = PhotoImage( Image.open(os.path.join(os.getcwd(), r'img\GPA_button.png'))) done_button_img = PhotoImage( Image.open(os.path.join(os.getcwd(), r'img\Done.png'))) # Buttons grades_button = Button(main_frame2, image=grades_button_img, bg='#4a6eb5', bd=0, command=lambda: grade_parser(username, password)) grades_button.place(relx=0.15, rely=0.43) grades_button.image = grades_button_img gpa_button = Button(main_frame2, image=gpa_button_img, bg='#4a6eb5', bd=0, command=gpa_parser) gpa_button.place(relx=0.15, rely=0.53) gpa_button.image = gpa_button_img done_button = Button(main_frame2, image=done_button_img, bg='#4a6eb5', bd=0, command=done) done_button.place(relx=0.18, rely=0.68) done_button.image = done_button_img # Screen for output # noinspection PyGlobalUndefined global textbox textbox = Text(main_frame2, font=('Arial', 9, 'bold'), fg='#1a1a1a', bg='#f2f2f2') textbox.insert( INSERT, '\n When you are done with the program\n please press done before closing.' ) textbox.place(relx=0.48, rely=0.43, relwidth=0.4, relheight=0.35)
def __init__( self, *, parent: Misc, workstation: WorkstationSettings, wallpaper: Image.Image, selection: Selection, ): super().__init__( parent, background=_BG_COLOR, borderwidth=0, highlightthickness=0, ) self._workstation = workstation self._workstation_coord_min = np.array((np.inf, np.inf)) self._workstation_coord_max = np.array((-np.inf, -np.inf)) for monitor in self._workstation.monitors: # TODO: convert settings to np.array while parsing self._workstation_coord_min = np.minimum( np.array(monitor.position), self._workstation_coord_min ) self._workstation_coord_max = np.maximum( np.array(monitor.position) + np.array(monitor.size), self._workstation_coord_max, ) self._canvas_size = np.ones(2) self._canvas_wallpaper_size = np.ones(2) self._canvas_wallpaper_position = np.zeros(2) self._wallpaper = wallpaper self._wallpaper_size = np.array(self._wallpaper.size) self._wallpaper_aspect_ratio = np.divide(*self._wallpaper_size) self._wallpaper_resized = self._wallpaper self._selection_visual = Image.new("RGBA", (1, 1)) self._selection_visual_draw = Draw(self._selection_visual) self._canvas_image_wallpaper = PhotoImage(self._wallpaper_resized) self._canvas_image_selection_visual = PhotoImage(self._selection_visual) self._selection = selection self._selection.register_onchange_handler(self.schedule_redraw) self._redraw_scheduled = False self._resize_scheduled = False self._show_monitor_labels = False self._show_unselected_area = True self._mouse_moving = False self._mouse_zooming = False self._mouse_zooming_anchor = np.zeros(2) self._mouse_last_coords = np.zeros(2) self._bind_actions() self._schedule_resize()
def leftClick(self, pos): x = pos[0] y = pos[1] buttonConfig = {'bd': 7, 'width': 15, 'height': 15, 'text': ' ', 'relief': 'raised', 'font': ['Montserrat', 11, 'bold'], 'compound': 'center'} if self.cellStateGrid[x, y] == Minesweeper.CELL_STATES.OPENED: return self.cellStateGrid[x, y] = Minesweeper.CELL_STATES.OPENED self.noOfUnopenedTiles -= 1 if self.bombGrid[x, y] == 1: image = PhotoImage(file=os.path.join(self.imagesDirectoryPath, 'exploredBomb.png')) buttonConfig['image'] = image buttonConfig['bg'] = '#BEA57D' self.buttonGrid[x][y].image = image self.buttonGrid[x][y].config(buttonConfig) self.revealAllBombs() messagebox.showerror(title='You Lost', message='Better Luck Next Time') sys.exit(0) elif self.convolvedMatrix[x, y] != 0: image = PhotoImage(file=os.path.join(self.imagesDirectoryPath, 'explored.png')) buttonConfig['image'] = image self.buttonGrid[x][y].config(buttonConfig) buttonConfig['bg'] = '#BEA57D' self.buttonGrid[x][y].image = image buttonConfig['text'] = self.convolvedMatrix[x, y] self.buttonGrid[x][y].config(buttonConfig) elif self.convolvedMatrix[x, y] == 0: image = PhotoImage(file=os.path.join(self.imagesDirectoryPath, 'explored.png')) buttonConfig['image'] = image buttonConfig['state'] = tk.DISABLED buttonConfig['relief'] = tk.FLAT buttonConfig['bg'] = '#BEA57D' self.buttonGrid[x][y].image = image self.buttonGrid[x][y].config(buttonConfig) if x - 1 > -1: if self.bombGrid[x - 1, y] != 1 and self.cellStateGrid[x - 1, y] != Minesweeper.CELL_STATES.OPENED: self.leftClick((x - 1, y)) if y + 1 < self.gridSize: if self.bombGrid[x, y + 1] != 1 and self.cellStateGrid[x, y + 1] != Minesweeper.CELL_STATES.OPENED: self.leftClick((x, y + 1)) if x + 1 < self.gridSize: if self.bombGrid[x + 1, y] != 1 and self.cellStateGrid[x + 1, y] != Minesweeper.CELL_STATES.OPENED: self.leftClick((x + 1, y)) if y - 1 > -1: if self.bombGrid[x, y - 1] != 1 and self.cellStateGrid[x, y - 1] != Minesweeper.CELL_STATES.OPENED: self.leftClick((x, y - 1)) if self.noOfUnopenedTiles == 0: self.endTime = time.time() self.seconds = (self.endTime - self.startTime) % 60 self.minutes = (self.endTime - self.startTime) / 60 messagebox.showinfo(title='You Won', message='Keep up the streak. Time taken to solve is: {} minutes and {} seconds'.format(int(self.minutes), int(self.seconds))) sys.exit(0)
def pre(): #after window after = Tk() after.title("After-Image") after.geometry('900x900') global path c = Canvas(after, width=400, height=400) c.pack() #This piece of code runs the python code for SuggestedDecay ##XMT images pre processing #reads the filepath Im = cv.imread(path) #nested for loops to run through the image array to check if the pixel number is between a certain color that corresponds to decay #this is where the fault is, the pixel range is not the corrent color for decay for x in range(0, len(Im)-1): for y in range(0, len(Im[x])-1): if (sum(Im[x][y]) < 336 and sum(Im[x][y]) > 315): #if its within the range color it red Im[x][y] = [255,0,0] else: #else keep it as it is Im[x][y] = Im[x][y] cv.imwrite("PreProcessed.png",Im) #displays the output image in after window my_image = PhotoImage(file="PreProcessed.png", master=after) c.create_image(0,0, image=my_image, anchor= NW) mes = Message(after, text="The first Pre Processing is done, you will find the image saved in your local folder", anchor =SW) mes.pack() #XMT Green #This part is further preprocessing where the suggested decay that is colored red is checked through looking around the pixel #and changing the pixel to green if neighboring pixels are also red #reads the filepath Im1 = cv.imread("PreProcessed.png") #sets the box of neighboring pixels boxsize = 15 #nested for loops to run through the image array for x in range(len(Im1)-51): for y in range(len(Im1)-51): redpixels = 0 #nested for loops to run through the box around selected pixel for i in range(boxsize): for j in range(boxsize): if np.array_equal(Im1[x+i][y+j], [255,0,0]): redpixels+=1 if redpixels/(boxsize*boxsize) > 0.5: for b in range(boxsize): for c in range(boxsize): Im1[x+b][y+c] = [0, 255, 0] cv.imwrite("GreenProcessed.png", Im1) #displays the output image in after window my_image1 = PhotoImage(file="GreenProcessed.png", master=after) c.create_image(0,30, image=my_image1, anchor= NW) mes = Message(after, text="The Second Pre Processing is done, you will find the image saved in your local folder", anchor =S) mes.pack() after.mainloop()
def create_widgets(self): self.hi_there = tk.Button(self) self.hi_there["text"] = "Hello World\n(click me)" self.hi_there["command"] = self.say_hi self.hi_there.pack(side="top") # Bouton Quitter self.quit = tk.Button(self, text="QUIT", fg="red", command=self.master.destroy) self.quit.pack(side="bottom") # Zone Graphique principal self.cnv = tk.Canvas(root, width=Largeur, height=Hauteur, bg="white") self.cnv.pack() # Fond d'ecran self.imageFond = Image.open("IMAGES/fondSpatial-1.jpeg") self.imgfondEcran = PhotoImage(self.imageFond) self.objImgFondEcran = self.cnv.create_image(Largeur // 2, Hauteur // 2, image=self.imgfondEcran) # Vaisseau pointe Bas self.imageV1 = Image.open("IMAGES/image-DestoyerImperial-3-Bas.png") self.imageV1 = self.imageV1.resize((150, 180), Image.ANTIALIAS) # The ( self.imgV1 = PhotoImage(self.imageV1) self.objImgV1 = self.cnv.create_image(Largeur // 2, Hauteur, image=self.imgV1) # Vaisseau pointe Droite self.imageV2 = Image.open("IMAGES/image-DestoyerImperial-3 Droite.png") self.imageV2 = self.imageV2.resize((150, 180), Image.ANTIALIAS) # The ( self.imgV2 = PhotoImage(self.imageV2) self.objImgV2 = self.cnv.create_image(Largeur, Hauteur // 2, image=self.imgV2) # faucon millenium self.image = Image.open("IMAGES/fauconMillenium.png") self.image = self.image.resize((30, 45), Image.ANTIALIAS) # The ( self.logo = PhotoImage(self.image) self.objImg = self.cnv.create_image(PosX, PosY, image=self.logo) # organisation image self.cnv.focus_set() self.cnv.tag_raise(self.objImg) # met faucon au 1er plan self.cnv.tag_lower(self.objImgV1) # met vaisseau self.cnv.tag_lower(self.objImgFondEcran) # arriere plan self.cnv.bind('<Key>', self.Clavier)
def load_images(): rectangle = PhotoImage( Image.open("img/character.png").resize( (int(UNIT * 2 / 3), int(UNIT * 2 / 3)))) triangle = PhotoImage( Image.open("img/obstacle.png").resize( (int(UNIT * 3 / 4), int(UNIT * 3 / 4)))) circle = PhotoImage( Image.open("img/end.png").resize( (int(UNIT * 2 / 3), int(UNIT * 2 / 3)))) return rectangle, triangle, circle
def create_content(self, **kw): self.minsize(50, 120) self._time = [0, 0, 0] self._on = False self._after_id = '' self.img_play = PhotoImage(master=self, file=IM_START) self.img_pause = PhotoImage(master=self, file=IM_PAUSE) self.img_stop = PhotoImage(master=self, file=IM_STOP) self.rowconfigure(2, weight=1) self.columnconfigure(0, weight=1) self.columnconfigure(1, weight=1) # --- GUI elements self.display = Label(self, text='%i:%.2i:%.2i' % tuple(self._time), anchor='center', style='timer.TLabel') self.intervals = Text(self, highlightthickness=0, relief='flat', height=3, width=1, inactiveselectbackground=self.style.lookup('TEntry', 'selectbackground')) self.intervals.tag_configure('center', justify='center') self.intervals.configure(state='disabled') self.b_interv = Button(self, text=_('Interval'), style='timer.TButton', command=self.add_interval) self.b_interv.state(('disabled',)) self.b_launch = Button(self, image=self.img_play, padding=2, command=self.launch, style='timer.TButton') self.b_stop = Button(self, image=self.img_stop, padding=2, command=self.stop, style='timer.TButton') # --- placement self.display.grid(row=0, columnspan=2, sticky='ew', padx=8, pady=(4, 0)) Label(self, text=_('Intervals:'), style='timer.TLabel').grid(row=1, columnspan=2, sticky='w', padx=4) self.intervals.grid(row=2, columnspan=2, sticky='eswn') self.b_interv.grid(row=3, columnspan=2, sticky='ew') self.b_launch.grid(row=4, column=0, sticky='ew') self.b_stop.grid(row=4, column=1, sticky='ew') self._corner = Sizegrip(self, style="timer.TSizegrip") self._corner.place(relx=1, rely=1, anchor='se') # --- bindings self.intervals.bind("<1>", lambda event: self.intervals.focus_set()) self.bind('<3>', lambda e: self.menu.tk_popup(e.x_root, e.y_root)) self.display.bind('<ButtonPress-1>', self._start_move) self.display.bind('<ButtonRelease-1>', self._stop_move) self.display.bind('<B1-Motion>', self._move) self.b_stop.bind('<Enter>', self._on_enter) self.b_stop.bind('<Leave>', self._on_leave)
def __init__(self, images): tk.Tk.__init__(self) self.count = len(images) self.index = 0 self.blank_shown = False self.blank = PhotoImage(file="img/Gun 10.jpg") self.photos = cycle(PhotoImage(file=image) for image in images) self.displayCanvas = tk.Label(self) self.displayCanvas.pack()
def cachepics(): for summoner in summoners: for card in summoner.deck: cardcaches[card] = {} cardcaches[card]['cardphoto'] = PhotoImage(Image.open(card.cardpicpath).resize((368, 240), Image.ANTIALIAS)) if 'picpath' in card.__dict__: pic = Image.open(card.picpath) if summoner.playernum is 1 or summoner.playernum is 2: #flip it if on right side of board pic = pic.transpose(FLIP_LEFT_RIGHT) cardcaches[card]['photo'] = PhotoImage(pic) else: #use the card pic as board pic if no board pic given cardcaches[card]['photo'] = PhotoImage(Image.open(card.cardpicpath).resize((100, 67), Image.ANTIALIAS)) summoner.faction.logophoto = PhotoImage(Image.open(summoner.faction.path + r'\symbol-lrg.png').resize((15, 15)))
def __init__(self, piece_color): self._popup_window = tkinter.Toplevel() self._color = piece_color self._choice_canvas = tkinter.Canvas( master = self._popup_window, width = 200, height = 200, background = 'white' ) self._choice_canvas.grid( row = 0, column = 0, padx = 0, pady = 0, sticky = tkinter.N + tkinter.S + tkinter.E + tkinter.W) self._choice_canvas.bind('<Configure>', self._on_canvas_resized) self._choice_canvas.bind('<Button-1>', self._on_canvas_clicked) self._popup_window.rowconfigure(0, weight=1) self._popup_window.columnconfigure(0, weight=1) self._clicked = False self.W_QUEEN = PhotoImage(file='W_Queen.gif') self.W_ROOK = PhotoImage(file='W_Rook.gif') self.W_BISHOP = PhotoImage(file='W_Bishop.gif') self.W_KNIGHT = PhotoImage(file='W_Knight.gif') self.B_QUEEN = PhotoImage(file='B_Queen.gif') self.B_ROOK = PhotoImage(file='B_Rook.gif') self.B_BISHOP = PhotoImage(file='B_Bishop.gif') self.B_KNIGHT = PhotoImage(file='B_Knight.gif')
def _add_left_menu(self): self.left_menu = tk.Frame(self.root, width=400, bg='red') self.left_menu.pack(side='left', fill='y') labels = ['x_min', 'x_max'] self.xrange_stringvars = [tk.StringVar() for _ in range(2)] self.xrange_entries = [ tk.Entry(self.left_menu, textvariable=v) for v in self.xrange_stringvars ] self.xrange_labels = [ tk.Label(self.left_menu, bg='gray', text=labels[i], font=("Arial", 8)) for i in range(2) ] for i, (e, l) in enumerate(zip(self.xrange_entries, self.xrange_labels)): l.place(x=10 + 65 * i, y=300, width=60, height=10) e.place(x=10 + 65 * i, y=312, width=60) e.delete(0, -1) e.insert(0, self.x_range[i]) e.bind('<Return>', self._reload_hist) labels = ['y_min', 'y_max'] self.yrange_stringvars = [tk.StringVar() for _ in range(2)] self.yrange_entries = [ tk.Entry(self.left_menu, textvariable=v) for v in self.yrange_stringvars ] self.yrange_labels = [ tk.Label(self.left_menu, bg='gray', text=labels[i], font=("Arial", 8)) for i in range(2) ] for i, (e, l) in enumerate(zip(self.yrange_entries, self.yrange_labels)): l.place(x=10 + 65 * i, y=700, width=60, height=10) e.place(x=10 + 65 * i, y=712, width=60) e.delete(0, -1) e.insert(0, self.y_range[i]) e.bind('<Return>', self._reload_hist) self.graph_x_img = PhotoImage(self.graphs[0], master=self.left_menu) self.graph_y_img = PhotoImage(self.graphs[1], master=self.left_menu) self.graph_x_frame = tk.Label(self.left_menu, image=self.graph_x_img) self.graph_y_frame = tk.Label(self.left_menu, image=self.graph_y_img) self.graph_x_frame.place(x=10, y=10) self.graph_y_frame.place(x=10, y=410)
def viewer(imgdir, kind=Toplevel, cols=None): """ измененная версия, размещает миниатюры по сетке """ win = kind() win.title('Viewer: ' + imgdir) thumbs = makeThumbs(imgdir) if not cols: cols = int(math.ceil(math.sqrt( len(thumbs)))) # фиксированное или N x N rownum = 0 savephotos = [] while thumbs: thumbsrow, thumbs = thumbs[:cols], thumbs[cols:] colnum = 0 for (imgfile, imgobj) in thumbsrow: photo = PhotoImage(imgobj) link = Button(win, image=photo) handler = lambda savefile=imgfile: ViewOne(imgdir, savefile) link.config(command=handler) link.grid(row=rownum, column=colnum) savephotos.append(photo) colnum += 1 rownum += 1 Button(win, text='Quit', command=win.quit).grid(columnspan=cols, stick=EW) return win, savephotos
def draw_path(): global path_img input = w.PathLeaf.get() tree_img = route_impl(current_tree, input) path_img = PhotoImage(Image.open(tree_img)) w.TreeCanvas.create_image(0, 0, image=path_img, anchor=tk.NW) w.TreeCanvas.update_idletasks()
def viewer(imgdir, kind=Toplevel, cols=None): """ custom version that lays out with fixed-size buttons """ win = kind() win.title('Viewer: ' + imgdir) thumbs = makeThumbs(imgdir) if not cols: cols = int(math.ceil(math.sqrt(len(thumbs)))) # fixed or N x N savephotos = [] while thumbs: thumbsrow, thumbs = thumbs[:cols], thumbs[cols:] row = Frame(win) row.pack(fill=BOTH) for (imgfile, imgobj) in thumbsrow: size = max(imgobj.size) # width, height photo = PhotoImage(imgobj) link = Button(row, image=photo) handler = lambda savefile=imgfile: ViewOne(imgdir, savefile) link.config(command=handler, width=size, height=size) link.pack(side=LEFT, expand=YES) savephotos.append(photo) Button(win, text='Quit', command=win.quit, bg='beige').pack(fill=X) return win, savephotos
def setupCanvas(self, arrival: str, currentMessage: Message, font: Font, fontColor: str): for part in sorted(currentMessage.parts, key=lambda x: x.sortOrder): if part.partType == "Pixel Gap": self.xCoord += int(part.value) elif part.partType == "Text": for char in part.value: self.canvas.create_text(self.xCoord, self.yCoord, fill=fontColor, text=char, font=font, tags="currentMessage", anchor=W) box = self.canvas.bbox(self.canvas.find_withtag("currentMessage")[-1]) self.xCoord = box[2] self.swapYCoords(arrival) elif part.partType == "Text From File": fileText = readFile(part.value) for char in fileText: self.canvas.create_text(self.xCoord, self.yCoord, fill=fontColor, text=char, font=font, tags="currentMessage", anchor=W) box = self.canvas.bbox(self.canvas.find_withtag("currentMessage")[-1]) self.xCoord = box[2] self.swapYCoords(arrival) elif part.partType == "Image": try: img = PhotoImage(Image.open(part.value)) self.images.append(img) self.canvas.create_image(self.xCoord, self.yCoord, image=img, anchor=W, tags="currentMessage") box = self.canvas.bbox(self.canvas.find_withtag("currentMessage")[-1]) self.xCoord = box[2] self.swapYCoords(arrival) except Exception as e: print("Error loading image: " + str(e))
def viewer(imgDir, kind=Toplevel, cols=None): """ make thumb links window for an image directory: one thumb button per image; use kind=Tk to show in main app window, or Frame container (pack); imgfile differs per loop: must save with a default; photoimage objs must be saved: erased if reclaimed; packed row frames (versus grids, fixed-sizes, canvas); """ win = kind() win.title('Viewer: ' + imgDir) quitBut = Button(win, text='Quit', command=win.quit, bg='beige') # pack first quitBut.pack(fill=X, side=BOTTOM) # so clip last thumbs = makeThumbs(imgDir) if not cols: cols = int(math.ceil(math.sqrt(len(thumbs)))) # fixed or N x N savephotos = [] while thumbs: thumbsrow, thumbs = thumbs[:cols], thumbs[cols:] row = Frame(win) row.pack(fill=BOTH) for (imgfile, imgobj) in thumbsrow: photo = PhotoImage(imgobj) link = Button(row, image=photo) handler = (lambda savefile=imgfile: ViewOne(imgDir, savefile)) link.config(command=handler) link.pack(side=LEFT, expand=YES) savephotos.append(photo) return win, savephotos
def initialize_food_img(self): """initializes the apple png used for the food""" img = Image.open("food.png") img = img.resize((int(SQUARE_WIDTH), int(SQUARE_WIDTH)), Image.ANTIALIAS) self.tk_img = PhotoImage(img)
def get_image(cells, screen_size): img = new('RGB', (size, size), "white") pixels = img.load() for x, y in list(cells): pixels[x, y] = (194, 232, 247) return PhotoImage(img.resize((screen_size, screen_size)))
def __init__(self): tk.Tk.__init__(self) self.photos = cycle(PhotoImage(file=image) for image in images) # self.printButton =Imagewindow(frame, image=image[0], command=self.nextPizza) self.title("Button GUI") self.displayCanvas = tk.Label(self) self.displayCanvas.pack()