class Hull(): """Hull class used as a superclass for all moving elements in game It is created with 3 requiered arguments: position on x-axis (int x), position on y-axis (int y), hull's image path (str image_path) And has 3 optional arguments speed on x-axis (int sx)[defaults to 0] speed on y-axis (int sy)[defaults to 0] speed is pixels/10ms object size compared to original photosize x:100 (int scale > 0)[defaults to 100] """ #Default constructor def __init__(self, x: float, y: float, image_path: str, sx: float = 0, sy: float = 0, scale: int = 100): #setting image to correct size self.image = PhotoImage(file = image_path) #TODO: add image scaling self.size = [self.image.width(), self.image.height()] self.x = x self.y = y #speed is in pixels/10ms self.sx = sx self.sy = sy self.size = [self.image.width(), self.image.height()] def get_radius(self) -> int: """Calculates objects radius""" n = min(self.size) n = n / 2 n = int(n) return n def get_image(self) -> PhotoImage: """Returns PhotoImage containing object's picture""" return self.image def draw(self, canvas: Canvas): """Draws object's picture on given canvas""" canvas.create_image(self.x - (self.size[0] / 2), \ self.y - (self.size[1] / 2), anchor = NW, image = self.image) def collision(self, other): """Checks collision with parameter object. If collision, returns true, else returns false""" distance = math.sqrt((abs(self.x - other.x) ** 2) \ + (abs(self.y - other.y)** 2)) if distance < self.get_radius() + other.get_radius(): return True else: return False
def load_image_from_file(self, file_name): image = PhotoImage(file=file_name) if image.width() != self.poser.image_size() or image.height() != self.poser.image_size(): message = "The loaded image has size %dx%d, but we require %dx%d." \ % (image.width(), image.height(), self.poser.image_size(), self.poser.image_size()) messagebox.showerror("Wrong image size!", message) self.source_image_label.configure(image=image, text="") self.source_image_label.image = image self.source_image_label.pack() self.source_image = extract_pytorch_image_from_filelike(file_name).to(self.torch_device).unsqueeze(dim=0)
class Jeu: def __init__(self): self.tk = Tk() self.tk.title("M.Filiforme court vers la sortie") self.tk.resizable(0, 0) self.tk.wm_attributes("-topmost", 1) self.canvas = Canvas(self.tk, width=500, height=500, \ highlightthicknes=0) self.canvas.pack() self.tk.update() self.hauteur_canevas = 500 self.largeur_canevas = 500 self.ap = PhotoImage(file='/home/vincent/Filiforme/arriere-plan.gif') larg = self.ap.width() haut = self.ap.height() for x in range(0, 5): for y in range(0, 5): self.canvas.create_image(x * larg, y * haut, \ image=self.ap, anchor='nw') self.lutins = [] self.enfonction = True def boucle_principale(self): while 1: if self.enfonction == True: for lutin in self.lutins: lutin.deplacer() self.tk.update_idletasks() self.tk.update() time.sleep(0.01)
def get_image(location, width, height): image = PhotoImage(data=Resource(location).resource) orig_width = image.width() orig_height = image.height() image = image.zoom(width, height) image = image.subsample(orig_width, orig_height) return image
def __enter__(self): # Hide the root while it is built. self.__root.withdraw() # Create components of splash screen. window = Toplevel(self.__root) canvas = Canvas(window) splash = PhotoImage(master=window, file=self.__file) # Get the screen's width and height. screen_width = window.winfo_screenwidth() screen_height = window.winfo_screenheight() # Get the images's width and height. img_width = splash.width() img_height = splash.height() # Compute positioning for splash screen. xpos = (screen_width - img_width) // 2 ypos = (screen_height - img_height) // 2 # Configure the window showing the logo. window.overrideredirect(True) window.geometry('+{}+{}'.format(xpos, ypos)) # Setup canvas on which image is drawn. canvas.configure(width=img_width, height=img_height, highlightthickness=0) canvas.grid() # Show the splash screen on the monitor. canvas.create_image(img_width // 2, img_height // 2, image=splash) window.update() # Save the variables for later cleanup. self.__window = window self.__canvas = canvas self.__splash = splash
def __init__(self, master=None, elements=None): Frame.__init__(self, master) self.root = master self.root.resizable(width=False, height=False) self.root.title('Simulacion') background_image = PhotoImage(file="world3.png") w = background_image.width() h = background_image.height() self.__background_image = background_image self.__canvas = Canvas(self.root, width=w, height=h) self.__canvas.h = h self.__canvas.w = w #self.__canvas.create_text((20, 20), text="Hola que tal", fill="black", anchor="nw") self.__canvas.create_image(0, 0, image=background_image, state="normal", anchor=NW) self.__canvas.pack() self._elements = elements self.createWidgets()
def drawImage(self, imgpil, forcesize=()): ''' Draws an image :param imgpil: :param forcesize: only if True, forces the size ''' imgtk = PhotoImage(image=imgpil) # not file=imgpath scrwide, scrhigh = forcesize or self.maxsize() # wm screen size x,y imgwide = imgtk.width() # size in pixels imghigh = imgtk.height() # same as imgpil.size fullsize = (0, 0, imgwide, imghigh) # scrollable viewwide = min(imgwide, scrwide) # viewable viewhigh = min(imghigh, scrhigh) canvas = self.canvas canvas.delete('all') # clear prior photo canvas.config(height=viewhigh, width=viewwide) # viewable window size canvas.config(scrollregion=fullsize) # scrollable area size canvas.create_image(0, 0, image=imgtk, anchor=NW) if imgwide <= scrwide and imghigh <= scrhigh: # too big for display? self.state('normal') # no: win size per img elif sys.platform[:3] == 'win': # do windows fullscreen self.state('zoomed') # others use geometry() self.saveimage = imgpil self.savephoto = imgtk # keep reference on me trace((scrwide, scrhigh), imgpil.size)
def load_image(self): file_name = filedialog.askopenfilename(filetypes=[("PNG", '*.png')], initialdir="data/illust") if len(file_name) > 0: image = PhotoImage(file=file_name) if image.width() != self.poser.image_size() or image.height( ) != self.poser.image_size(): message = "The loaded image has size %dx%d, but we require %dx%d." \ % (image.width(), image.height(), self.poser.image_size(), self.poser.image_size()) messagebox.showerror("Wrong image size!", message) self.source_image_label.configure(image=image, text="") self.source_image_label.image = image self.source_image_label.pack() self.source_image = extract_pytorch_image_from_filelike( file_name).to(self.torch_device).unsqueeze(dim=0) self.needs_update = True
def __init__(self, imgdir, imgfile): Toplevel.__init__(self) self.title(imgfile) imgpath = os.path.join(imgdir, imgfile) imgobj = PhotoImage(file=imgpath) Label(self, image=imgobj).pack() print(imgpath, imgobj.width(), imgobj.height()) # size in pixels self.savephoto = imgobj # keep reference on me
class WorldClock: FILENAME = "dates.json" def __init__(self, master): self.master = master self.canvas = Canvas(self.master, width = 300, height = 300) self.master.title("World Clock") self.canvas.pack() self.dir = os.getcwd() self.photo = PhotoImage(file = self.dir + "/icon.png") self.button = Button(self.master, image = self.photo, command = self.showSettings) self.button.image = self.photo self.button.place( relx = 1.0, rely = 0, x = (-1 * math.ceil(self.photo.width() / 2)), y = math.ceil(self.photo.height() / 2), anchor = "c" ) self.showDates() def changeTimeFormatToNumber(self, timeformat): times = timeformat.split(":") hour = int(times[0]) minute = int(times[1]) return hour + (minute / 60) def getTimeFromTimezone(self, timestamp): currentTime = calendar.timegm(time.gmtime()) cet = pytz.timezone("CET") offset = cet.utcoffset(datetime.now()) utc = currentTime + (3600 * (-1 * self.changeTimeFormatToNumber(str(offset)))) date = datetime.fromtimestamp((utc + (3600 * self.changeTimeFormatToNumber(timestamp)))) return date #.strftime("%A, %d %b, %Y %H:%M:%S") def showDates(self): try: handle = open(self.dir + "/" + self.FILENAME) content = handle.read() content = json.loads(content) for obj in content: self.updateCanvas(obj["city"], self.getTimeFromTimezone(obj["timezone"])) except (FileNotFoundError, JSONDecodeError): print("File Not found") def updateCanvas(self, city, time): print(city, time) def showSettings(self): print("Show Settings")
class Platform(Sprite): def __init__(self, game, x, y, gifimage): Sprite.__init__(self, game) self.gifimage = PhotoImage(file=gifimage) self.image = self.game.canvas.create_image(x, y, image=self.gifimage, \ anchor='nw') self.coordinates = Coords(x, y, \ x + self.gifimage.width(), \ self.gifimage.height())
def format_image(self, file, ratio): assert (ratio >= 1), "Ratio must be bigger than 1!" my_path = "images/" + str(file) + ".gif" image = PhotoImage(file = my_path) sfx = image.width() / self.size sfy = image.height() / self.size sf = int(min(sfx, sfy) * ratio) new_image = image.subsample(sf, sf) return new_image
def load_image(self): file_name = filedialog.askopenfilename(filetypes=[("PNG", '*.png')], initialdir="images") if len(file_name) > 0: image = PhotoImage(file=file_name) if image.width() != self.image_size[-1] or image.height( ) != self.image_size[-2]: message = "The loaded image has size %dx%d, but we require %dx%d." \ % (image.width(), image.height(), self.image_size[-1], self.image_size[-2]) messagebox.showerror("Wrong image size!", message) self.source_image_label.configure(image=image, text="") self.source_image_label.image = image self.source_image_label.pack() self.source_image = extract_numpy_image_from_filelike(file_name) cuda.memcpy_htod(self.device_inputs[0], self.source_image) cuda.memcpy_htod(self.device_inputs[2], self.base_grid) self.needs_update = True
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 load_image_from_file(self, file_name=None, generate=False): if generate: image = self.process_image(input="generate") else: image = self.process_image(img_path=file_name) image.save('./data/illust/loaded_image.png') image = PhotoImage(file='./data/illust/loaded_image.png') if image.width() != self.poser.image_size() or image.height( ) != self.poser.image_size(): message = "The loaded image has size %dx%d, but we require %dx%d." \ % (image.width(), image.height(), self.poser.image_size(), self.poser.image_size()) messagebox.showerror("Wrong image size!", message) self.source_image_label.configure(image=image, text="") self.source_image_label.image = image self.source_image_label.pack() self.source_image = extract_pytorch_image_from_filelike( './data/illust/loaded_image.png').to( self.torch_device).unsqueeze(dim=0) os.remove('./data/illust/loaded_image.png')
def makebw(img: tk.PhotoImage) -> tk.PhotoImage: ''' Make black&white version of image Args: img: image to convert ''' for x in range(img.width()): for y in range(img.height()): bw = sum(img.get(x, y)) // 3 if bw in (0, 255): continue img.put('#{0:02x}{0:02x}{0:02x}'.format(bw), (x, y)) return img
def set_next_image_to_frame(self, event=None): previous_text = self.entry_set.get() if self.__current_tk_image: self.__img_db[self.__current_dirname]['dir'] = previous_text # Delete tk images self.canvas.delete(tk.ALL) self.__current_tk_image = [] try: self.__current_dirname = self.__dirnames.pop() except IndexError: return self.__end_configuration() img_list = self.__img_db[self.__current_dirname]["thumbs"] self.entry_set.delete(0, len(previous_text)) self.entry_set.insert(0, self.__current_dirname) border = 10 cpt = 0 for image in img_list: imgobj = PhotoImage(file=image) _x = imgobj.width()/2 + imgobj.width()*(cpt % 2) + border _y = imgobj.height()/2 + imgobj.height()*int(cpt/2) + border cpt += 1 self.canvas.create_image(_x, _y, image=imgobj) self.__current_tk_image.append(imgobj) self.entry_set.focus_set()
class Game: def on_closing(self): self.running = False def __init__(self): self.window = Tk() self.window.title("Mr. Stick Man Races for the Exit") self.window.resizable(0, 0) self.window.wm_attributes("-topmost", 1) self.window.protocol("WM_DELETE_WINDOW", self.on_closing) self.canvas = Canvas(self.window, width=CANVAS_WIDTH, height=CANVAS_HEIGHT, highlightthickness=0) self.canvas.pack() self.window.update() self.canvas_height = CANVAS_HEIGHT self.canvas_width = CANVAS_WIDTH self.bg_tile_image = PhotoImage(file="images/background.png") self.alt_bg_tile_image = PhotoImage(file="images/background1.png") bg_tile_width = self.bg_tile_image.width() bg_tile_height = self.bg_tile_image.height() for x in range(0, NUM_LEFT_RIGHT_BACKGROUND_TILES): for y in range(0, NUM_UP_DOWN_BACKGROUND_TILES): if (x + y) % 2 == 0: background = self.bg_tile_image else: background = self.alt_bg_tile_image self.canvas.create_image(x * bg_tile_width, y * bg_tile_height, image=background, anchor='nw') self.sprites = [] self.running = True def mainloop(self): while 1: if self.running: for sprite in self.sprites: sprite.move() self.window.update_idletasks() self.window.update() time.sleep(0.005)
class ImageTex2D(Texture2D): def __init__(self, filename, scale=1.0): Texture2D.__init__(self) self.filename = filename self.image = PhotoImage(file=filename) self.val_scale = scale self.xres = self.image.width() self.yres = self.image.height() self.norm_scale = scale / 255.0 def Sample(self, uv): x = int(self.xres * uv[0]) % self.xres y = self.yres - int(self.yres * uv[1]) % self.yres - 1 return (mul(self.image.get(x, y), self.norm_scale))
def open_click(self, event): f = filedialog.askopenfilename(filetypes=[('All files', '*.*'), ('PNG pictures', '*.png'), ('JPEG pictures', '*.jpg')], defaultextension='.jpg') if f: new = PhotoImage(file=f) images = self.canvas.find_withtag('result') for p in images: self.canvas.delete(p) width, height = new.width(), new.height() self.img_width, self.img_height = width, height self.canvas.create_image(width // 2, height // 2, image=new, state='normal', tag='result') self.image = new
def draw_image(cv, url): global withpil, im root.title("Python Image Viewer - {0}".format(url)) if withpil: im = Image.open(url) imsize = im.size cvsize = get_objsize(cv) ratio, newpos, newsize = cal_fitsize(imsize, cvsize) imresize = im.resize(newsize) pi = ImageTk.PhotoImage(image=imresize) else: pi = PhotoImage(file=url) #wrap with pillow resized im imsize = pi.width(), pi.height() cvsize = get_objsize(cv) ratio, newpos, newsize = cal_fitsize(imsize, cvsize) pi = pi.zoom(ratio) # placing in canvas cv.delete(ALL) cv.image = pi #https://stackoverflow.com/a/37214188 cv.create_image(newpos[0], newpos[1], anchor=NW, image=pi) return 1
def PhotoImageFromLink(link, width=None, height=None, scale=None): base64_data = downloadImage(link) image = PhotoImage(data=base64_data) (old_w, old_h) = (image.width(), image.height()) if scale != None: width = int(old_w * scale) height = int(old_h * scale) (target_w, target_h) = (width, height) if (target_w != None and target_h != None): x_common = math.gcd(target_w, old_w) x_zoom = int(target_w / x_common) x_sub = int(old_w / x_common) y_common = math.gcd(target_h, old_h) y_zoom = int(target_h / y_common) y_sub = int(old_h / y_common) image = image.zoom(x_zoom, y_zoom) image = image.subsample(x_sub, y_sub) return image
class Splash(Toplevel): def __init__(self, parent): from tkinter import Label, PhotoImage from tkinter.ttk import Progressbar Toplevel.__init__(self, parent) self.title("Splash") self.overrideredirect(True) screenwidth = self.winfo_screenwidth() screenheight = self.winfo_screenheight() width = round(screenwidth / 30) * 10 height = round(screenheight / 30) * 10 self.gif1 = PhotoImage(file='timg.gif') old_width = self.gif1.width() old_height = self.gif1.height() scale_w = width/old_width scale_h = (height-20)/old_height if scale_h < 1: scale_h = 1 / scale_h if scale_w < 1: scale_w = 1 / scale_w self.gif1 = self.gif1.subsample(int(scale_w), int(scale_h)) self.label = Label(self, image=self.gif1) self.label.config(width=width, height=height-20, bg='white', bd=1) self.pgb = Progressbar(self, orient='horizontal', length=width, mode='determinate') self.geometry('%dx%d+%d+%d' % (width, height, (screenwidth - width)/2, (screenheight - height)/2)) self.label.pack(side='top', fill='both') self.pgb.pack(side='bottom', fill='both') # required to make window show before the program gets to the mainloop self.update()
class Floater(Prey): def __init__(self, x, y): self.gif = PhotoImage(file = 'ufo.gif') self.angle = 0 self.speed = 5 Prey.__init__(self, x, y, self.gif.width(), self.gif.height(),self.angle, self.speed) self.randomize_angle() def goodspeed(self): if 3 <= self.speed <= 7: return True else: return False def update(self, m): if random() <= 0.3: self.speed = self.speed + uniform(-0.5, 0.5) self.angle = self.angle + uniform(-0.5, 0.5) if not Floater.goodspeed(self): self.angle = self.angle + uniform(-0.5, 0.5) self.move() def display(self, canvas): canvas.create_image(*self.get_location(), image = self.gif)
if sys.version_info[0] == 3: # Python 3 from tkinter import Tk, PhotoImage else: from Tkinter import Tk, PhotoImage 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 eye_images(eyetracker): root = Tk() print( "Subscribing to eye images for eye tracker with serial number {0}.".format( eyetracker.serial_number)) eyetracker.subscribe_to(tr.EYETRACKER_EYE_IMAGES, eye_image_callback, as_dictionary=True) # Wait for eye images. time.sleep(2)
class IO: def __init__(self, thread): # set up screen, width = 512, height = 256 self.mythread = thread self.screen = Tk() self.screen.title("Jarvis Simulator") self.screen.geometry("512x256+1600+500") self.screen.wm_maxsize(width=512, height=256) self.screen.wm_minsize(width=512, height=256) self.screen.wm_resizable(width=False, height=False) self.image = PhotoImage(width = 512, height = 256) self.label = Label(self.screen, image=self.image) self.label.grid() # set up keyboard for c in self.Keycodes.keys(): exec("self.screen.bind(\"<%s>\", self.%s)" % (c, c)) self.screen.bind("<Any-KeyPress>", self.KeyPressed) self.screen.bind("<Any-KeyRelease>", self.KeyReleased) system("xset r off") self.screen.protocol("WM_DELETE_WINDOW", self.delete_callback) def delete_callback(self): system("xset r on") self.mythread.stop() self.screen.destroy() KBD = 0 Keycodes = { "Return" : 128, "BackSpace" : 129, "Left" : 130, "Up" : 131, "Right" : 132, "Down" : 133, "Home" : 134, "End" : 135, "Prior" : 136, "Next" : 137, "Insert" : 138, "Delete" : 139, "Escape" : 140 } for i in range(1,13): k = { "F" + str(i) : 140+i } Keycodes.update(k) for key in Keycodes.keys(): code = Keycodes[key] exec("""def %s(self, event): self.KBD = %s if debugKBD: print(%s)""" % (key, code, code)) def KeyPressed(self, event): if event.char: self.KBD = ord(event.char) if debugKBD: print(str(ord(event.char))) def KeyReleased(self, event): self.KBD = 0 if debugKBD: print("Key Released.\n") def drawFill(self, color): horizontal_line = "{" + " ".join([color]*self.image.width()) + "}" self.image.put(" ".join([horizontal_line] * self.image.height())) def drawPoint(self, x, y, color): #~ print("Drawing %s point at (%i, %i)" % (color, x, y)) self.image.put(color, (x, y)) def drawmem(self, location, value): (y, x) = divmod(location,32) x = x * 16 memword = binary(value, bits=16) for i in range(0, 16): if memword[15-i] == '1': self.drawPoint(x+i, y, "green") else: self.drawPoint(x+i, y, "black")
class MyLittleVideoGame: def __init__(self, window, title, backgroundfilenamePNG="", backgroundcolor="#cba428", canvasWidth=320, canvasHeight=569): self.title = title self.font = ("Courier", 21, "bold") self.window = window self.backgroundcolor = backgroundcolor self.window.configure(bg=self.backgroundcolor) self.window.winfo_toplevel().title(self.title) self.window.resizable(False, False) self.score = 0 self.lives = 3 self.level = 1 self.other = "" # make labels and canvas self.labelScore = Label(window, text="SCORE: " + str(self.score), font=self.font, bg=self.backgroundcolor) self.labelLives = Label(window, text=" LIVES: " + str(self.lives), font=self.font, bg=self.backgroundcolor) self.labelLevel = Label(window, text=" LEVEL: " + str(self.level), font=self.font, bg=self.backgroundcolor) self.labelOther = Label(window, text=self.other, font=self.font, bg=self.backgroundcolor) # if there is not background file, make small screen canvas if backgroundfilenamePNG != "": self.backgroundPhotoImage = PhotoImage(file=backgroundfilenamePNG) self.canvasWidth = self.backgroundPhotoImage.width() self.canvasHeight = self.backgroundPhotoImage.height() else: self.canvasWidth = canvasWidth self.canvasHeight = canvasHeight if canvasWidth <= 320: self.font = ("Courier", 14, "bold") elif canvasWidth > 320 and canvasWidth < 450: self.font = ("Courier", 18, "bold") self.refreshScoreboard() self.canvas = Canvas(window, width=self.canvasWidth, height=self.canvasHeight, bg=self.backgroundcolor) if backgroundfilenamePNG != "": try: self.backgroundCanvasImage = self.canvas.create_image( 1, 0, image=self.backgroundPhotoImage, anchor=NW) # ,tag="background") except: print(self.backgroundPhotoImage + " not found, or otherwise could not be loaded.") self.messageXPosition = self.canvasWidth // 2 self.messageYPosition = self.canvasHeight // 2 self.labelScore.grid(row=0, column=0) self.labelLevel.grid(row=0, column=1) self.labelOther.grid(row=0, column=2) self.labelLives.grid(row=0, column=3) self.canvas.grid(row=1, column=0, columnspan=4) self.key = "" self.movex = 0 self.movey = 0 self.space = False self.left = False self.right = False self.up = False self.down = False self.escape = False self.paused = False self.messageOnScreen = False self.simpleKey = "" self.backgroundMusicLoop = None self.isBackGroundMusicPlaying = False self._bindEscapeKey() self._bindControlKeys() def refreshScoreboard(self): # make labels and canvas self.labelScore = Label(self.window, text="SCORE: " + str(self.score), font=self.font, bg=self.backgroundcolor) self.labelLives = Label(self.window, text=" LIVES: " + str(self.lives), font=self.font, bg=self.backgroundcolor) self.labelLevel = Label(self.window, text=" LEVEL: " + str(self.level), font=self.font, bg=self.backgroundcolor) self.labelOther = Label(self.window, text=self.other, font=self.font, bg=self.backgroundcolor) def getCanvasHeight(self): # returns height of canvas return (self.canvasHeight) def getCanvasWidth(self): # returns width of canvas return (self.canvasWidth) def setTitle(self, title): self.title = title self.window.winfo_toplevel().title(self.title) def _backgroundDelete(self): # removes background and leaves blank canvas self.canvas.delete(self.backgroundCanvasImage) self.window.update() # loads a background image file, sets the canvas to image width, loads image def backgroundLoad(self, fileName): self.backgroundPhotoImage = PhotoImage(file=fileName) self.canvasWidth = self.backgroundPhotoImage.width() self.canvasHeight = self.backgroundPhotoImage.height() self.canvas.config(width=self.canvasWidth, height=self.canvasHeight) self.backgroundCanvasImage = self.canvas.create_image( 1, 0, image=self.backgroundPhotoImage, anchor=NW) self.canvas.tag_lower(self.backgroundCanvasImage, "all") self.window.update() # changes background by deleting background and loading one in. def backgroundChange(self, fileName): self._backgroundDelete() self.backgroundLoad(fileName) def getScore(self): # returns score return (self.score) def setScore(self, score): self.score = score # sets score and displays self.labelScore.configure(text="SCORE: " + str(self.score)) self.window.update() def addToScore(self, addToScoreThisAmount): self.score = self.score + int(addToScoreThisAmount) self.labelScore.configure(text="SCORE: " + str(self.score)) self.window.update() def subtractFromScore(self, subtractFromScoreThisAmount): self.score = self.score - int(subtractFromScoreThisAmount) self.labelScore.configure(text="SCORE: " + str(self.score)) self.window.update() def getLives(self): return (self.lives) def setLives(self, lives): self.lives = lives self.labelLives.configure(text="LIVES: " + str(self.lives)) self.window.update() def addLives(self, livesToAdd): self.lives = self.lives + int(livesToAdd) self.labelLives.configure(text="LIVES: " + str(self.lives)) self.window.update() def subtractLives(self, livesToSubtract): self.lives = self.lives - int(livesToSubtract) self.labelLives.configure(text="LIVES: " + str(self.lives)) self.window.update() def getLevel(self): return (self.level) def setLevel(self, level): self.level = level self.labelLevel.configure(text="LEVEL: " + str(self.level)) self.window.update() def increaseLevel(self, increaseLevelByThisAmount): self.level = self.level + int(increaseLevelByThisAmount) self.labelLevel.configure(text="LEVEL: " + str(self.level)) self.window.update() def getOther( self): # other is a string, could be anything you want displayed return (self.other) def setOther(self, whateverString ): # other is a string, could be anything you want displayed self.other = whateverString self.labelOther.configure(text=self.other) self.window.update() # play background music while game is playing. Supply mp3 filename, and volume which is a float (0.0to1.0)ex .7 def playBackgroundMusic(self, backgroundMusicfileName): self.backgroundMusicLoop = loopsound(backgroundMusicfileName) return (self.backgroundMusicLoop) # play background music while game is playing. Supply mp3 filename, and volume which is a float (0.0to1.0)ex .7 # def playBackgroundMusic(self, backgroundMusicfileName, optionalForMp3s_CheckRestartHowOften=.2): # self.backgroundMusicLoop = loopsound( # backgroundMusicfileName, optionalForMp3s_CheckRestartHowOften) # return(self.backgroundMusicLoop) # stop background music, maybe between switching levels or similar def stopBackgroundMusic(self, backgroundMusicLoopObject): stoploop(backgroundMusicLoopObject) # this is not for playing background music, this is for playing short things like an explosion or firing a shot def playSoundandKeepGoing(self, fileName): return (soundplay(fileName)) def playSoundAndPauseWhilePlaying(self, fileName): return (soundplay(fileName, block=True)) # this places a text message in the middle of the screen, remove before showing another def showMessage(self, messageText): self.window.update() self.messageXPosition = self.canvasWidth // 2 self.messageYPosition = self.canvasHeight // 2 self.message = self.canvas.create_text(self.messageXPosition, self.messageYPosition, text=messageText, font=self.font) self.messageOnScreen = True self.window.update() def moveMessage(self, Xmove, Ymove): self.canvas.move(self.message, Xmove, Ymove) self.messageXPosition = self.messageXPosition + Xmove self.messageYPosition = self.messageYPosition + Ymove self.window.update() def isMessageOnScreen(self): return (self.messageOnScreen) def deleteMessage(self): self.canvas.delete(self.message) self.messageOnScreen = False self.window.update() """ This is used when there is a game pause. Like press Y to continue for example. Background music will play, but keypress must happen for it to break out of loop and continue """ # game will pause until a keypress occurs, also returns the keypress def waitForKeyPress(self): self._unbindControlKeys() self.keyPress = "" while (self.keyPress == ""): self.window.bind("<Key>", lambda e: self._reportKeyPress(e)) time.sleep(.3) self.window.update() self._bindControlKeys() return (self.keyPress) # sets value of the keypress which is then returned in the waitForKeyPress method def _reportKeyPress(self, e): # print(e.keysym) self.keyPress = e.keysym def destroyAllObjects(self): self.canvas.delete("all") def sleep(self, timeInSeconds): # sleeps/pauses game for however many seconds time.sleep(timeInSeconds) self.window.update() def _bindControlKeys(self): self.window.bind("<KeyPress-Left>", lambda e: self._left()) self.window.bind("<KeyPress-Right>", lambda e: self._right()) self.window.bind("<KeyRelease-Left>", lambda e: self._stopLeft()) self.window.bind("<KeyRelease-Right>", lambda e: self._stopRight()) self.window.bind("<KeyPress-Up>", lambda e: self._up()) self.window.bind("<KeyPress-Down>", lambda e: self._down()) self.window.bind("<KeyRelease-Up>", lambda e: self._stopUp()) self.window.bind("<KeyRelease-Down>", lambda e: self._stopDown()) self.window.bind("<KeyPress-p>", lambda e: self._pausePress(e)) self.window.bind("<KeyPress-space>", lambda e: self._space(e)) self.window.bind("<KeyRelease-space>", lambda e: self._stopSpace(e)) self.window.update() def _unbindControlKeys(self): self.window.unbind("<KeyPress-Left>") self.window.unbind("<KeyPress-Right>") self.window.unbind("<KeyRelease-Left>") self.window.unbind("<KeyRelease-Right>") self.window.unbind("<KeyPress-Up>") self.window.unbind("<KeyPress-Down>") self.window.unbind("<KeyRelease-Up>") self.window.unbind("<KeyRelease-Down>") self.window.unbind("<KeyPress-p>") self.window.unbind("<KeyPress-space>") self.window.unbind("<KeyRelease-space>") self.window.update() # returns if left or right was pressed and returns the amount to move def getMoves(self): # , leftXamount, rightXamount, upYamount,downYamount): self.window.update() return [self.left, self.right, self.up, self.down] def getLeft(self): return (self.left) def getRight(self): return (self.right) def getUp(self): return (self.up) def getDown(self): return (self.down) def getSpace(self): return (self.space) def _left(self): self.left = True def _right(self): self.right = True def _stopLeft(self): self.left = False def _stopRight(self): self.right = False def _up(self): self.up = True def _down(self): self.down = True def _stopUp(self): self.up = False def _stopDown(self): self.down = False def _space(self, e): self.space = True def _stopSpace(self, e): self.space = False def _pausePress(self, e): self.paused = True self.waitForKeyPress() self.paused = False # binds esc to exit game def _bindEscapeKey(self): self.window.bind("<KeyPress-Escape>", lambda e: self._escape(e)) self.window.bind("<KeyRelease-Escape>", lambda e: self._stopEscape(e)) return (self.escape) def _escape(self, e): self.escape = True self.exitProgram() def exitProgram(self): self.stopBackgroundMusic(self.backgroundMusicLoop) self.window.destroy()
class GUIZeroImage(): def __init__(self, image_source, width, height): """ GUIZeroImage manages an "image" for guizero widgets, parsing its contents, sizing it accordingly and managing environment. :param string image_source: The source of the image, a file path, PIL or Tk image object. :param int width: The required width of the image, set to `None`, to keep the original image width :param int height: The required height of the image, set to `None`, to keep the original image width. """ self._image_source = image_source self._pil_image = None self._tk_image = None self._tk_frames = [] self._width = width self._height = height self._current_frame = 0 self._animation = False self._animation_running = False # open the image self._setup_image() @property def image_source(self): """ Returns the original source of the image, be that a file path, PIL or Tk image object. """ return self._image_source @property def tk_image(self): """ Returns the Tk PhotoImage object. """ return self._tk_image @property def pil_image(self): """ Returns the PIL Image object. """ return self._pil_image @property def width(self): """ Returns the image width. """ return int(self._width) @property def height(self): """ Returns the image height. """ return int(self._height) @property def animation(self): """ Returns `True` if the image contains more than 1 frame (i.e. is an animation) """ return self._animation @property def tk_frames(self): """ Returns a list of frames as Tk PhotoImage objects which make up this image. """ return self._tk_frames def _setup_image(self): try: # open image self._open_image_source() # size image self._size_image() # open frames self._open_image_frames() except Exception as e: error_text = "Image import error - '{}'\n".format(e) error_text += "Check the file path and image type is {}".format("/".join(system_config.supported_image_types)) raise_error(error_text) def _open_image_source(self): if system_config.PIL_available: if isinstance(self._image_source, str): # the source is a string, so try and open as a path self._pil_image = Image.open(self._image_source) self._tk_image = ImageTk.PhotoImage(self._pil_image) elif Image.isImageType(self._image_source): # the source is a PIL Image self._pil_image = self._image_source self._tk_image = ImageTk.PhotoImage(self._pil_image) elif isinstance(self._image_source, (PhotoImage, ImageTk.PhotoImage)): self._tk_image = self._image_source else: raise Exception("Image must be a file path, PIL.Image or tkinter.PhotoImage") else: if isinstance(self._image_source, str): self._tk_image = PhotoImage(file=self._image_source) elif isinstance(self._image_source, PhotoImage): self._tk_image = self._image_source else: raise Exception("Image must be a file path or tkinter.PhotoImage") def _size_image(self): # if there is no size, set it to the image width if self._width is None: self._width = self._tk_image.width() if self._height is None: self._height = self._tk_image.height() # does it need resizing? if self._width != self._tk_image.width() or self._height != self._tk_image.height(): if self._pil_image: resized_image = self._pil_image.resize((self._width, self._height), Image.ANTIALIAS) self._tk_image = ImageTk.PhotoImage(resized_image) else: error_format("Image resizing - cannot scale the image as PIL is not available.") def _open_image_frames(self): if self._pil_image: frame_count = 0 try: while True: self._pil_image.seek(frame_count) tk_frame = ImageTk.PhotoImage(self._pil_image.resize((self._width, self._height), Image.ANTIALIAS)) try: delay = self._pil_image.info['duration'] except: delay = 100 self._tk_frames.append((tk_frame, delay)) frame_count += 1 except EOFError as e: # end of frames pass if frame_count > 1: self._animation = True
""" show one image with standard tkinter photo object; as is this handles GIF files, but not JPEG images; image filename listed in command line, or default; use a Canvas instead of Label for scrolling, etc. """ import os import sys from tkinter import Tk, Label, PhotoImage # use standard tkinter photo object IMGDIR = 'images' IMGFILE = sys.argv[1] if len( sys.argv) > 1 else 'london-2010.gif' # cmdline argument given? # GIF works, but JPEG requires PIL IMGPATH = os.path.join(IMGDIR, IMGFILE) win = Tk() win.title(IMGFILE) imgobj = PhotoImage(file=IMGPATH) # display photo on a Label Label(win, image=imgobj).pack() print(imgobj.width(), imgobj.height()) # show size in pixels before destroyed win.mainloop()
class AboutDialog: """ About dialog box class """ def __init__(self, app): """ Initialise Toplevel dialog """ self.__app = app # Reference to main application class self.__master = self.__app.get_master() # Reference to root class (Tk) self._dialog = Toplevel() self._dialog.title = DLGABOUT self._dialog.geometry("+%d+%d" % (self.__master.winfo_rootx() + 50, self.__master.winfo_rooty() + 50)) self._dialog.attributes("-topmost", "true") self.body() def body(self): """ Set up widgets """ # Create widgets self.lbl_title = Label(self._dialog, text=DLGABOUT) self.lbl_title.config(font=("Verdana", 16)) self.thumb = PhotoImage(file=THUMBNAIL) self.can = Canvas( self._dialog, width=self.thumb.width(), height=self.thumb.height(), cursor="hand2", ) self.can.create_image(0, 0, image=self.thumb, anchor=NW) self.lbl_desc = Label(self._dialog, text=ABOUTTXT, wraplength=300) self.lbl_version = Label(self._dialog, text=f"PyMandel Version: {VERSION}") self.lbl_numba_version = Label(self._dialog, text=f"Numba Version: {numba_ver}") self.lbl_numpy_version = Label(self._dialog, text=f"Numpy Version: {numpy_ver}") self.lbl_copyright = Label(self._dialog, text=COPYRIGHTTXT, fg="blue", cursor="hand2") self.lbl_colorcet = Label(self._dialog, text=COLORCETTXT, fg="blue", cursor="hand2") self.btn_ok = Button(self._dialog, text="OK", width=8, command=self.ok_press) # Arrange widgets self.lbl_title.grid(column=0, row=0, padx=5, pady=5) self.can.grid(column=0, row=1, padx=5, pady=5) self.lbl_desc.grid(column=0, row=2, padx=5, pady=5) self.lbl_version.grid(column=0, row=3, padx=5) self.lbl_numba_version.grid(column=0, row=4, padx=5) self.lbl_numpy_version.grid(column=0, row=5, padx=5) self.lbl_copyright.grid(column=0, row=6, padx=5, pady=5) self.lbl_colorcet.grid(column=0, row=7, padx=5, pady=5) self.btn_ok.grid(column=0, row=8, ipadx=3, ipady=3, padx=5, pady=5) # Bind commands and hotkeys self.can.bind("<Button-1>", lambda e: open_new_tab(WIKIURL)) self.lbl_copyright.bind("<Button-1>", lambda e: open_new_tab(GITHUBURL)) self.lbl_colorcet.bind("<Button-1>", lambda e: open_new_tab(CETURL)) self.btn_ok.bind("<Return>", self.ok_press) self.btn_ok.focus_set() def ok_press(self, *args, **kwargs): """ Handle OK button press """ self.__master.update_idletasks() self._dialog.destroy()
class Spaceship: #create spaceship object and its according properties and values def __init__(self, canvas): self.__canvas = canvas self.__imgSpaceship = PhotoImage(file="images/spaceship.png") self.__imgExplosion = PhotoImage(file='images/exploded_ship.png') self.__width = self.__imgSpaceship.width() self.__height = self.__imgSpaceship.height() self.__xpos = 0 self.__ypos = self.__canvas.winfo_reqheight() // 2 - self.__height // 2 self.__spaceship = self.__canvas.create_image( self.__xpos, self.__ypos, image=self.__imgSpaceship, anchor="nw") def move(self, x, y): #stop the spaceship from leaving the screen if 0 <= x <= self.__canvas.winfo_reqwidth() - self.__width - 5: self.__xpos = x if 60 <= y <= self.__canvas.winfo_reqheight() - self.__height - 5: self.__ypos = y self.__canvas.coords(self.__spaceship, self.__xpos, self.__ypos) def getLeftSide(self): """ Returns the x position of the left side of the spaceship RETURNS: -------- int The x position of the left side of the spaceship """ return self.__xpos def getTopSide(self): """ Returns the y position of the top side of the spaceship RETURNS: -------- int The y position of the top side of the spaceship """ return self.__ypos def getRightSide(self): """ Returns the x position of the right side of the spaceship RETURNS: -------- int The x position of the right side of the spaceship """ return self.__xpos + self.__width def getBottomSide(self): """ Returns the y position of the bottom of the spaceship RETURNS: -------- int The y position of the bottom side of the spaceship """ return self.__ypos + self.__height def getWidth(self): """ Returns the width of the spaceship in pixels RETURNS: -------- int The width of the spaceship in pixels """ return self.__width def getHeight(self): """ Returns the height of the spaceship in pixels RETURNS: -------- int The height of the spaceship in pixels """ return self.__height def getImg(self): """ Returns a boolean value to signify the image of the spaceship RETURNS: -------- bool Value to signify if img is ship or explosion """ if self.__imgSpaceship == self.__imgExplosion: return 0 else: return 1 def setImage(self): """ Set the image of the spaceship to an explosion """ self.__imgSpaceship = self.__imgExplosion self.__canvas.itemconfig(self.__spaceship, image=self.__imgSpaceship) def deleteShip(self): #delete(hide) the spaceship self.__xpos, self.__ypos = 0, 200 self.__canvas.coords(self.__spaceship, self.__xpos, self.__ypos) self.__imgSpaceship = PhotoImage(file="images/spaceship.png") self.__canvas.itemconfig(self.__spaceship, image=self.__imgSpaceship)
class HeadingIndicator(): def __init__(self, root): self.root = root #load image to canvas self.gauge = PhotoImage(file="gauge.png") self.canvas = Canvas(self.root) self.canvas.create_image(200, 200, image=self.gauge) self.canvas.pack(expand=YES, fill=BOTH) self.canvas.config(width=self.gauge.width(), height=self.gauge.height()) #key bindings self.root.bind('<Left>', self.moveLeft) self.root.bind('<Right>', self.moveRight) #indicator parameters self.center = [200, 200] self.lineLength = 180 self.lineWidth = 4 self.indicator = [] self.angle = 0 self.angleReference = [random.randint(0, 1) for i in range(100)] self.updateIndicator(self.angle) self.angleReferenceGenerator() self.root.mainloop() def updateIndicator(self, angle): angle = angle * pi / 180 point1 = self.center - np.matrix( [self.lineLength * sin(angle), self.lineLength * cos(angle)]) point2 = point1 + np.matrix( [self.lineWidth * cos(angle), -self.lineWidth * sin(angle)]) point3 = self.center + np.matrix( [self.lineWidth * cos(angle), -self.lineWidth * sin(angle)]) edge1 = [ceil(point1[0, 0]), ceil(point1[0, 1])] edge2 = [ceil(point2[0, 0]), ceil(point2[0, 1])] edge3 = [ceil(point3[0, 0]), ceil(point3[0, 1])] self.indicator = self.canvas.create_polygon(self.center, edge1, edge2, edge3, fill='red') def moveLeft(self, event): self.angle = self.angle + 2 self.canvas.delete(self.indicator) self.updateIndicator(self.angle) def moveRight(self, event): self.angle = self.angle - 2 self.canvas.delete(self.indicator) self.updateIndicator(self.angle) def angleReferenceGenerator(self): global total_angle_disp if self.angleReference: popped = self.angleReference.pop() if popped == 1: self.angle = self.angle + 2 else: self.angle = self.angle - 2 self.canvas.delete(self.indicator) self.updateIndicator(self.angle) self.root.after(100, self.angleReferenceGenerator) total_angle_disp += abs(self.angle) self.w = Message( text=f"Total angle displacement: {total_angle_disp:.0f}°", bg='white', fg='black', width=75) self.w.place(relx=0.095, rely=0.06, anchor=CENTER)
""" Canvas image example 2 """ from sys import argv from tkinter import Tk, Canvas, PhotoImage, BOTH, NW win = Tk() GIFDIR = "../gifs/" FILENAME = argv[1] if len(argv) > 1 else 'ora-lp4e.gif' # name on cmdline? IMG = PhotoImage(file=GIFDIR + FILENAME) can = Canvas(win) can.pack(fill=BOTH) can.config(width=IMG.width(), height=IMG.height()) # size to IMG size can.create_image(2, 2, image=IMG, anchor=NW) win.mainloop()