class Pulsator(Black_Hole): counter = 30 death = 15 def __init__(self,x,y,size = 30): Black_Hole.__init__(self,x,y) self.set_dimension(size, size) self._image = PhotoImage(Image.open('space_amoeba.gif').convert('RGBA').resize((size, size), Image.ANTIALIAS)) self.radius = (self._image.height()/2)+((self._image.width()**2)/(8 * self._image.height())) self._counter = 1 def update(self, model): result = Black_Hole.update(self,model) self._counter += 1 if len(result) > 0: self.set_dimension(self.get_dimension()[0] + len(result), self.get_dimension()[1] + len(result)) self._image = PhotoImage(Image.open('space_amoeba.gif').convert('RGBA').resize((self.get_dimension()[0], self.get_dimension()[1]), Image.ANTIALIAS)) self.radius = (self._image.height()/2)+((self._image.width()**2)/(8 * self._image.height())) self._counter = 1 if self._counter == Pulsator.counter: self.set_dimension(self.get_dimension()[0] - 1, self.get_dimension()[1] - 1) self._image = PhotoImage(Image.open('space_amoeba.gif').convert('RGBA').resize((self.get_dimension()[0], self.get_dimension()[1]), Image.ANTIALIAS)) self.radius = (self._image.height()/2)+((self._image.width()**2)/(8 * self._image.height())) self._counter = 1 if self.get_dimension() < (Pulsator.death,Pulsator.death): result.add(self) return result
class Black_Hole(Simulton): def __init__(self,x,y): self._image = PhotoImage(file='Black_Hole.gif') Simulton.__init__(self,x,y,self._image.width(),self._image.height()) self.radius = (self._image.height()/2)+((self._image.width()**2)/(8 * self._image.height())) def update(self, model): from hunter import Hunter result = set() for item in model.find(lambda item:isinstance(item, Prey) or isinstance(item,Hunter)): if self.contains(item): result.add(item) return result def contains(self,s): if not isinstance(s,tuple): s = (s.get_location()[0],s.get_location()[1]) return math.sqrt((self.get_location()[0] - s[0])**2 + (self.get_location()[1] - s[1])**2) <= self.radius def display(self,canvas): canvas.create_image(*self.get_location(),image=self._image)
class PreviewWin(Toplevel): def __init__(self, title, image, filename='New file', icon=None): super().__init__() if icon: self.iconbitmap(icon) self.filename = filename self.title(title) self.image = image preview = image.resize((600, 800), Image.ADAPTIVE) self.thumbs = PhotoImage(preview) self._makeWidgets() self.configure(width=600, height=600) # TODO установить размер окна по дефолту self.grab_set() self.focus_set() self.wait_window() def _makeWidgets(self): button_frm = Frame(self) button_frm.pack(side=BOTTOM, fill=X, padx=3, pady=3) save = Button(button_frm, text='Сохранить') save.configure(command=self.handlerSave) save.pack(side=RIGHT) canvas = Canvas(self, bg='white', relief=SUNKEN, width=self.thumbs.width(), height=self.thumbs.height(), scrollregion=(0, 0, self.thumbs.width(), self.thumbs.height())) canvas.create_image(0, 0, image=self.thumbs, anchor=NW) scrolly = Scrollbar(self) scrollx = Scrollbar(self, orient=HORIZONTAL) scrolly.pack(side=RIGHT, fill=Y) scrollx.pack(side=BOTTOM, fill=X) canvas.pack(expand=1, fill=BOTH) scrolly.configure(command=canvas.yview) scrollx.configure(command=canvas.xview) canvas.configure(xscrollcommand=scrollx.set, yscrollcommand=scrolly.set) def handlerSave(self): ftype = [('Document PDF', '*.pdf'), ('Image PNG', '*.png')] file = asksaveasfilename(filetypes=ftype, initialfile=self.filename, defaultextension='.pdf') if file: if file.endswith('pdf'): out_image = self.image.resize((2000, 2829), Image.ADAPTIVE) im = out_image.convert('RGB') im.save(file, 'PDF') else: self.image.save(file, 'PNG')
class Floater(Prey): # inherit prey def __init__(self, x, y): self._image = PhotoImage(file='ufo.gif') Prey.__init__(self, x, y, self._image.width(), self._image.height(), 0, 5) self.randomize_angle() def update(self, model): if random.randrange(0, 10) / 10 <= 0.3: # 30% time changed if (self.get_speed() + random.randrange(0, 10) / 10 - 0.5) >= 0.3: if (self.get_speed() + random.randrange(0, 10) / 10 - 0.5) <= 0.7: new_speed = (self.get_speed() + random.randrange(0, 10) / 10 - 0.5) else: new_speed = 7 else: new_speed = 3 self.set_velocity( new_speed, self.get_angle() + random.randrange(0, 10) / 10 - 0.5) self.move() def display(self, root_canvas): root_canvas.create_image(self._x, self._y, image=self._image)
def make_canvas(self): """ Criação do canvas para edição da máscara de correção """ h = Scrollbar(self.root, orient=HORIZONTAL) v = Scrollbar(self.root, orient=VERTICAL) self.canvas = Canvas(self.root, scrollregion=(0, 0, 1000, 1000), yscrollcommand=v.set, xscrollcommand=h.set) h['command'] = self.canvas.xview v['command'] = self.canvas.yview self.canvas.grid(column=0, row=0, sticky=(N,W,E,S)) h.grid(column=0, row=1, sticky=(W,E)) v.grid(column=1, row=0, sticky=(N,S)) self.root.grid_columnconfigure(0, weight=1) self.root.grid_rowconfigure(0, weight=1) if self.image: imgtk = PhotoImage(image=Image.open(self.image)) # not file=imgpath imgwide = imgtk.width() # size in pixels imghigh = imgtk.height() # same as imgpil.size fullsize = (0, 0, imgwide, imghigh) # scrollable self.canvas.delete('all') # clear prior photo self.canvas.config(height=imgwide, width=imghigh) # viewable window size self.canvas.config(scrollregion=fullsize) # scrollable area size self.imageid=self.canvas.create_image(0, 0, image=imgtk, anchor=NW) self.images.append(imgtk) self.canvas.bind("<Button-1>", self.xy) self.canvas.bind("<B1-Motion>", self.add_rectangle) self.canvas.bind("<B1-ButtonRelease>", self.done_stroke) self.canvas.bind_all('<Button-2>', self.select) self.canvas.bind_all('<B2-Motion>', self.on_drag) self.canvas.bind_all("<B2-ButtonRelease>", self.update_item) self.canvas.bind('<Button-3>', self.config_item) self.canvas.bind_all('<Delete>',self.delete_item) self.canvas.focus()
class Floater(Prey): radius_constant = 5 def __init__(self,x,y):#,angle, speed): #radius_constant = 5 self._gif = PhotoImage(file = 'ufo.gif') Prey.__init__(self,x,y, self._gif.width(), self._gif.height(), 0, Floater.radius_constant) def update(self):#,model):#,model):#,model): a = self.get_angle() b = self.get_speed() # new if randint(1,10) <= 3: a = self.get_angle() variable_five = .5 fixed_variable_int = 7 fixed_variable_int_two = 3 b = self.get_speed() final_movement = min(fixed_variable_int,max(fixed_variable_int_two,b + random()-variable_five)) self.set_velocity(final_movement, a + random()-variable_five) self.move() self.wall_bounce() # self.move() def display(self,canvas): canvas.create_image(self._x, self._y, image=self._gif)
def display_image(image: ImageTk.PhotoImage) -> None: global img_container img_container = Label( root, image=image, width=image.width(), height=image.height()) img_container.image = image img_container.grid(row=1, column=0)
def pil_image_dir(): from PIL.ImageTk import PhotoImage imgdir = 'images' if len(sys.argv) > 1: imgdir = sys.argv[1] imgfiles = os.listdir(imgdir) main = Tk() main.title('Image Viewer') quit = Button( main, text='Quit all', command=main.quit, font=('courier', 25)) quit.pack() savephotos = [] for imgfile in imgfiles: imgpath = os.path.join(imgdir, imgfile) win = Toplevel() win.title(imgfile) try: imgobj = PhotoImage(file=imgpath) Label(win, image=imgobj).pack() print(imgpath, imgobj.width(), imgobj.height()) savephotos.append(imgobj) except Exception: errmsg = 'skipping %s\n%s' % (imgfile, sys.exc_info()[1]) Label(win, text=errmsg).pack() main.mainloop()
class Floater(Prey): radius = 5 def __init__(self, x, y): self.ufo = PhotoImage(file='ufo.gif') self.randomize_angle() ufo_width = self.ufo.width() ufo_height = self.ufo.height() Prey.__init__(self, x, y, ufo_width, ufo_height, self.get_angle(), 5) def update(self, model): random_time = random() if random_time <= 0.3: random_speed_num = random() if random_speed_num < 0.5 and -random_speed_num > -0.5: self.random_speed = self.get_speed() + random_speed_num if self.random_speed > 3.0 and self.random_speed < 7.0: self.set_speed(self.random_speed) random_angle_num = random() if random_angle_num < 0.5 and -random_angle_num > -0.5: self.random_angle = self.get_angle() + random_angle_num self.set_angle(self.random_angle) self.move() def display(self, the_canvas): the_canvas.create_image(*self.get_location(), image=self.ufo)
def drawImage(self, imgpil, forcesize=()): """ 将图片绘制在窗体的canvas中 """ 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#否则若为windows系统则使窗体全屏 self.state('zoomed') # others use geometry() self.saveimage = imgpil #PIL.Image类型 self.savephoto = imgtk # keep reference on me #PIL.ImageTk.PhotoImage,保持图片引用 trace((scrwide, scrhigh), imgpil.size)
def image_canvas_simple(): win = Tk() img = PhotoImage(file=gifdir+'ora-lp4e.gif') can = Canvas(win) can.pack(fill=BOTH) can.config(width=img.width(), height=img.height()) can.create_image(2, 2, image=img, anchor=NW) win.mainloop()
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()) self.savephoto = imgobj #Keep reference on me
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()) # 像素大小 self.savephoto = imgobj # 保留对图片的引用
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
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()) # размер в пикселях self.savephoto = imgobj # сохранить ссылку на изображение
class Hunter(Pulsator,Mobile_Simulton): sightDistance = 200 death = 10 def __init__(self,x,y,size = 20): Pulsator.__init__(self,x,y) Mobile_Simulton.__init__(self, x, y, self.radius, self.radius, random.random()*math.pi*2,5) self.set_dimension(size, size) self._image = PhotoImage(Image.open('deathstar.gif').convert('RGBA').resize((size, size), Image.ANTIALIAS)) self.radius = (self._image.height()/2)+((self._image.width()**2)/(8 * self._image.height())) def update(self, model): result = set() all_prey = model.find(lambda item:isinstance(item, Prey)) for item in all_prey: if self.contains(item): result.add(item) self._counter += 1 closest = self.sightDistance existing = all_prey - result for item in existing: if self.distance(item.get_location()) < closest: closest = self.distance(item.get_location()) self.set_angle(math.atan2(item.get_location()[1] - self.get_location()[1], item.get_location()[0] - self.get_location()[0])) if len(result) > 0: self.set_dimension(self.get_dimension()[0] + len(result), self.get_dimension()[1] + len(result)) self._image = PhotoImage(Image.open('deathstar.gif').convert('RGBA').resize((self.get_dimension()[0], self.get_dimension()[1]), Image.ANTIALIAS)) self.radius = (self._image.height()/2)+((self._image.width()**2)/(8 * self._image.height())) self._counter = 1 if self._counter == 30: self.radius -= 1 self.set_dimension(self.get_dimension()[0] - 1, self.get_dimension()[1] - 1) self._image = PhotoImage(Image.open('deathstar.gif').convert('RGBA').resize((self.get_dimension()[0], self.get_dimension()[1]), Image.ANTIALIAS)) self.radius = (self._image.height()/2)+((self._image.width()**2)/(8 * self._image.height())) self._counter = 1 self.move() if self.get_dimension() < (Hunter.death,Hunter.death): result.add(self) return result
def pil_image_viewer(): from PIL.ImageTk import PhotoImage imgdir = 'images' imgfile = 'florida-2009-1.jpg' if len(sys.argv) > 1: imgfile = sys.argv[1] imgpath = os.path.join(imgdir, imgfile) win = Tk() win.title(imgfile) imgobj = PhotoImage(file=imgpath) Label(win, image=imgobj).pack() win.mainloop() print(imgobj.width(), imgobj.height())
class Floater(Prey): def __init__(self,x,y): self._image=PhotoImage(file='ufo.gif') Prey.__init__(self,x,y,self._image.width(),self._image.height(),random()*math.pi*2,5) def update(self): if random()*100<30: self._angle+=random()-0.5 self._speed+=random()-0.5 elif random()<0.5: self._angle+=random()-0.5 else: self._angle+=random()-0.5 if self._speed<3: self._speed=3 elif self._speed>7: self._speed=7 self.move() def display(self,canvas): sw,sh=(int(i) for i in self.get_dimension()) iw,ih=self._image.width(),self._image.height() if sw!=iw or sh!=ih: self._image = PhotoImage(Image.open('ufo.gif').resize((sw,sh), Image.ANTIALIAS)) canvas.create_image(*self.get_location(),image=self._image)
class Special(Simulton): def __init__(self,x,y): self._image = PhotoImage(Image.open('bigbang.gif').convert('RGBA').resize((20, 20), Image.ANTIALIAS)) Simulton.__init__(self,x,y,self._image.width(),self._image.height()) self._center = (int(x),int(y)) self._explosion = 500 def update(self, model): self._explosion = model.world()[1]/2 all_swallowed = True if self.get_dimension() >= model.world(): model.big_bang = None elif self.get_dimension() >= (self._explosion,self._explosion): total = model.world() for item in model.items: item.set_location(random.uniform(1,total[0] - 1),random.uniform(1,total[1] - 1)) self.set_dimension(total[0], total[1]) else: for item in model.items: location = item.get_location() location = (int(location[0]),int(location[1])) if location != self._center: all_swallowed = False if location[0] < self._center[0]: new_x = location[0] + 1 elif location[0] > self._center[0]: new_x = location[0] - 1 else: new_x = location[0] if location[1] < self._center[1]: new_y = location[1] + 1 elif location[1] > self._center[1]: new_y = location[1] - 1 else: new_y = location[1] item.set_location(new_x,new_y) else: self.change_dimension(1, 1) self._image = PhotoImage(Image.open('bigbang.gif').convert('RGBA').resize((self.get_dimension()[0], self.get_dimension()[1]), Image.ANTIALIAS)) if all_swallowed: self.change_dimension(10, 10) self._image = PhotoImage(Image.open('bigbang.gif').convert('RGBA').resize((self.get_dimension()[0], self.get_dimension()[1]), Image.ANTIALIAS)) def display(self,canvas): canvas.create_image(*self.get_location(),image=self._image)
class Ball(Prey): radius = 5 def __init__(self,x,y): self._image = PhotoImage(file='asteroid.gif') Prey.__init__(self,x,y,self._image.width(),self._image.height(),random.random()*math.pi*2,5) def update(self,model): self.move() return set() def display(self,canvas): canvas.create_image(*self.get_location(),image=self._image)
def onOpen(self): self.onStop() name = askdirectory() if name: self.images = [(x, PhotoImage(file=name + '/' + x)) for x in os.listdir(name)] #print(self.images) if self.drawn: self.canvas.delete(self.drawn) img = PhotoImage(file=name + '/' + self.images[0][0]) self.canvas.config(height=img.height(), width=img.width()) self.drawn = self.canvas.create_image(2, 2, image=img, anchor=NW) self.canvas.update() #print(self.drawn) self.image = name + '/' + self.images[0][0], img
class Floater(Prey): def __init__(self,x,y): self._image = PhotoImage(file='ufo.gif') Prey.__init__(self,x,y,self._image.width(),self._image.height(),0,5) self.randomize_angle() def update(self,model): if random() <= .3: new_speed = min(7,max(3,self.get_speed() + random()-.5)) self.set_velocity(new_speed, self.get_angle()+random()-.5) self.move() def display(self,the_canvas): the_canvas.create_image(self._x,self._y,image=self._image)
class Floater(Prey): def __init__(self, x, y): self._image = PhotoImage(file='ufo.gif') self.randomize_angle() Prey.__init__(self, x, y, self._image.width(), self._image.height(), self.get_angle(), 5) def update(self, model): if random() <= 0.3: if random() <= 0.5: self.set_angle(self.get_angle() + random() * 0.5) if self.get_speed() + random() * 0.5 >= 3.0 and self.get_speed( ) + random() * 0.5 <= 7.0: self.set_speed(self.get_speed() + random() * 0.5) self.move() def display(self, canvas): canvas.create_image(*self.get_location(), image=self._image)
class Floater(Prey): def __init__(self,x,y): self._image = PhotoImage(file='enterprise.gif') Prey.__init__(self,x,y,self._image.width(),self._image.height(),random.random()*math.pi*2,5) def update(self,model): if random.randint(1,10) <= 3: speed_difference = random.uniform(-0.5, 0.5) if self.get_speed() + speed_difference >= 3 and self.get_speed() + speed_difference <= 7: self.set_speed(self.get_speed() + speed_difference) self.set_angle(self.get_angle() + random.uniform(-0.5, 0.5)) self.move() return set() def display(self,canvas): canvas.create_image(*self.get_location(),image=self._image)
class Floater(Prey): def __init__(self,x,y): self._image = PhotoImage(file='ufo.gif') Prey.__init__(self,x,y,self._image.width(),self._image.height(),0,5) Prey.randomize_angle(self) def update(self, speed): Prey.move(self) Prey.wall_bounce(self) if random() <= .3: speed_mult,rad_mult = uniform(-.5,.5),uniform(-.5,.5) while self._speed + speed_mult > 3 and self._speed + speed_mult < 7: self._speed += speed_mult self._angle += rad_mult def display(self, canvas): canvas.create_image(*self.get_location(),image=self._image)
class Floater(Prey): radiusc = 5 def __init__(self,x,y): self.randomize_angle() self.pic = PhotoImage(file = 'ufo.gif') Prey.__init__(self,x,y,self.pic.width(),self.pic.height(),self._angle,5) def update(self,model): con = randrange(1,100) if con <= 30: change = randrange(-500,500)/1000 + self._speed if 3 < change < 7: self._speed = change change = randrange(-500,500)/1000 self._angle += change else: pass self.move() def display(self,the_canvas): the_canvas.create_image(*self.get_location(),image=self.pic)
class Floater(Prey): def __init__(self, x, y): self._image = PhotoImage(file='ufo.gif') Prey.__init__(self, x, y, self._image.width(), self._image.height(), 2 * math.pi * random.random(), 5) def update(self, model): temp = random.randint(1, 10) if temp <= 3: #change angle and speed a = random.choice('+-') b = random.choice('+-') changedby1 = int(str(a) + str(random.randint(0, 5))) * .1 changedby2 = int(str(b) + str(random.randint(0, 5))) * .1 if ((self.get_speed() + changedby1) <= 7) or ( (self.get_speed() + changedby1) >= 3): self.set_speed(self.get_speed() + changedby1) self.set_angle(self.get_angle() + changedby2) self.move() def display(self, the_canvas): the_canvas.create_image(*self.get_location(), image=self._image)
class Floater(Prey): def __init__(self, x, y, width=0, height=0, angle=0, speed=5): Prey.__init__(self, x, y, width, height, angle, speed) self.radius = 5 self._image = PhotoImage(file="ufo.gif") self.randomize_angle() self.set_dimension(self._image.width(), self._image.height()) self.set_speed(speed) def update(self): rand_num = random() if rand_num <= 0.3: # changed speed_change = random() - 0.5 angle_change = (random() - 0.5) * math.pi if 3 <= self.get_speed() <= 7: self.set_speed(self.get_speed() + speed_change) self.set_angle(self.get_angle() + angle_change) self.move() def display(self, canvas): canvas.create_image(self.get_location(), image=self._image)
def drawImage(self, imgpil, forcesize=()): 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 drawImage(self, imgpil, forcesize=()): imgtk = PhotoImage(image=imgpil) scrwide, scrhigh = forcesize or self.maxsize() imgwide = imgtk.width() imghigh = imgtk.height() fullsize = (0, 0, imgwide, imghigh) viewwide = min(imgwide, scrwide) viewhigh = min(imghigh, scrhigh) canvas = self.canvas canvas.delete('all') canvas.config(height=viewhigh, width=viewwide) canvas.config(scrollregion=fullsize) canvas.create_image(0, 0, anchor=NW, image=imgtk) if imgwide <= scrwide and imghigh <= scrhigh: self.state('normal') elif sys.platform[:3] == 'win': self.state('zoomed') self.saveimage = imgpil self.savephoto =imgtk trace((scrwide, scrhigh), imgpil.size)
def drawImage(self, imgpil, forcesize=()): imgtk = PhotoImage(image=imgpil) # 非文件 = 图像路径 scrwide, scrhigh = forcesize or self.maxsize() # wm 屏幕大小 x,y imgwide = imgtk.width() # 像素大小 imghigh = imgtk.height() # 和 imgpil.size 一样 fullsize = (0, 0, imgwide, imghigh) # 可滚动的 viewwide = min(imgwide, scrwide) # 可浏览的 viewhigh = min(imghigh, scrhigh) canvas = self.canvas canvas.delete('all') # 清除先前的照片 canvas.config(height=viewhigh, width=viewwide) # 可浏览的窗口大小 canvas.config(scrollregion=fullsize) # 可滚动的区域大小 canvas.create_image(0, 0, image=imgtk, anchor=NW) if imgwide <= scrwide and imghigh <= scrhigh: # 太大不能显示? self.state('normal') # 否: 赢得每个图像的大小 if sys.platform[:3] == 'win': # 窗口全屏 self.state('zoomed') # 其它使用 geometry() self.saveimage = imgpil self.savephoto = imgtk # 一直参考我 trace((scrwide, scrhigh), imgpil.size)
""" отображает изображение с помощью альтернативного объекта из пакета PIL поддерживает множество форматов изображений; предварительно установите пакет PIL: поместите его в каталог Lib\site-packages """ import os, sys, random from glob import glob # чтобы получить список файлов по расширению from tkinter import * from PIL.ImageTk import PhotoImage # <== использовать альтернативный класс из # PIL, остальной программный код # без изменений imgdir = 'D:/Projects/python/Gifs/' files = glob(imgdir + '*') images = [x for x in files] imgfile = random.choice(images) if len(sys.argv) > 1: imgfile = sys.argv[1] imgpath = os.path.join(imgdir, imgfile) win = Tk() win.title(imgfile) imgobj = PhotoImage(file=imgpath) # теперь поддерживает и JPEG! imgfile = random.choice(images) Label(win, image=imgobj).pack() win.mainloop() print(imgobj.width(), imgobj.height()) # показать размер в пикселях при выходе
import sys from tkinter import * from PIL.ImageTk import PhotoImage imgdir = "..\Images\\" if len(sys.argv) > 1: imgdir = sys.argv[1] imgfiles = os.listdir(imgdir) # 不包括目录前缀 main = Tk() main.title('Viewer') quit = Button(main, text='Quit all', command=main.quit, font=('courier', 25)) quit.pack() savephotos = [] for imgfile in imgfiles: imgpath = os.path.join(imgdir, imgfile) win = Toplevel() win.title(imgfile) try: imgobj = PhotoImage(file=imgpath) Label(win, image=imgobj).pack() print(imgpath, imgobj.width(), imgobj.height()) savephotos.append(imgobj) except: errmsg = 'skipping %s \n%s' % (imgfile, sys.exc_info()[1]) Label(win, text=errmsg).pack() mainloop()
""" show one image with PIL photo replacement object handles many more image types; install PIL first: placed in Lib\site-packages """ import os, sys from Tkinter import * from PIL.ImageTk import PhotoImage # <== use PIL replacement class # rest of code unchanged imgdir = 'images' imgfile = 'florida-2009-1.jpg' # does gif, jpg, png, tiff, etc. if len(sys.argv) > 1: imgfile = sys.argv[1] imgpath = os.path.join(imgdir, imgfile) win = Tk() win.title(imgfile) imgobj = PhotoImage(file=imgpath) # now JPEGs work! Label(win, image=imgobj).pack() win.mainloop() print(imgobj.width(), imgobj.height()) # show size in pixels on exit
#!usr/local/bin/python #coding: utf-8 ''' Created on 2016年3月6日 @author: Calvin Wang ''' from tkinter import * from PIL.ImageTk import PhotoImage import sys,os imgdir = 'F:\Python\images' imgfile = '331018.jpg' if len(sys.argv) > 1: imgdir = sys.argv[1] imgpath = os.path.join(imgdir,imgfile) win = Tk() win.title(imgfile) imgobj = PhotoImage(file=imgpath) Label(win,image=imgobj).pack() print(imgobj.width(),imgobj.height()) win.mainloop()
""" import os, sys from tkinter import * from PIL.ImageTk import PhotoImage # <== required for JPEGs and others imgdir = 'images' if len(sys.argv) > 1: imgdir = sys.argv[1] imgfiles = os.listdir(imgdir) # does not include directory prefix main = Tk() main.title('Viewer') quit = Button(main, text='Quit all', command=main.quit, font=('courier', 25)) quit.pack() savephotos = [] for imgfile in imgfiles: imgpath = os.path.join(imgdir, imgfile) win = Toplevel() win.title(imgfile) try: imgobj = PhotoImage(file=imgpath) Label(win, image=imgobj).pack() print(imgpath, imgobj.width(), imgobj.height()) # size in pixels savephotos.append(imgobj) # keep a reference except: errmsg = 'skipping %s\n%s' % (imgfile, sys.exc_info()[1]) Label(win, text=errmsg).pack() main.mainloop()
""" import os, sys from Tkinter import * from PIL.ImageTk import PhotoImage # <== required for JPEGs and others imgdir = '/Users/arman/Public/Assets' if len(sys.argv) > 1: imgdir = sys.argv[1] imgfiles = os.listdir(imgdir) # does not include directory prefix main = Tk() main.title('Viewer') quit = Button(main, text='Quit all', command=main.quit, font=('courier', 25)) quit.pack() savephotos = [] for imgfile in imgfiles: imgpath = os.path.join(imgdir, imgfile) win = Toplevel() win.title(imgfile) try: imgobj = PhotoImage(file=imgpath) Label(win, image=imgobj).pack() print(imgpath, imgobj.width(), imgobj.height()) # size in pixels savephotos.append(imgobj) # keep a reference except: errmsg = 'skipping %s\n%s' % (imgfile, sys.exc_info()[1]) Label(win, text=errmsg).pack() main.mainloop()
from tkinter import * # GIF works, but JPEG requires PIL imgfile1 = 'ora-pp3e.gif' imgfile2 = 'ora-lp4e.jpg' win = Tk() # make root first win.title('%s and %s' % (imgfile1, imgfile2)) imgobj1 = PhotoImage(file=imgfile1) # display standard photo on a Label Label(win, image=imgobj1).pack() print(imgobj1.width(), imgobj1.height()) # show size in pixels before destroyed from PIL.ImageTk import PhotoImage imgobj2 = PhotoImage(file=imgfile2) # display PIL photo on a Label Label(win, image=imgobj2).pack() print(imgobj2.width(), imgobj2.height()) # show size in pixels before destroyed win.mainloop()
def refreshWidget(self) : #print "refresh" self.card_win.pack_forget() import unicodedata #Card window self.card_win = PanedWindow(self.card_win.master, orient=VERTICAL) self.card_win.pack(side=TOP, expand=True, fill=BOTH, pady=2, padx=2) #Create the name zone name_zone=PanedWindow(self.card_win, orient=HORIZONTAL) name = StringVar() name.set(self.name) def modifName(*args) : try : assert('"' not in name.get()) name.get().encode('ascii') except Exception as e: print ("error on name") name.set(self.name) return old = self.name in Card.blocked_creature self.name=name.get() if old or self.name in Card.blocked_creature : self.refreshWidget() name.trace("w", modifName) name_wid=Entry(name_zone, width=30,textvariable=name) name_wid.pack() name_zone.add(name_wid) #Create the cost ad star stringvar #print int(floor(self.getCost())) self.cost=StringVar() self.stars=StringVar() cost_wid=Label(None, textvariable=self.cost, background='red',width=5, anchor=W) star_wid=Label(None, textvariable=self.stars, background='blue', anchor=E) self.cost.set(str(int(floor(self.getCost())))) self.stars.set("*"*self.getStars()) #Add them in name zone name_zone.add(cost_wid) name_zone.add(star_wid) #Create an Image Zone image_zone=Button(self.card_win, command=self.choosePhoto) if hasattr(self,"photofile") and self.photofile : print ("Image: ",self.photofile) try : pilImage=Image.open(self.photofile) img=PhotoImage(pilImage,master=image_zone) except : decomp=self.photofile.split('/') for i in range(1,6) : try : fname="/".join(decomp[-i:]) print ("try to open",fname) pilImage = Image.open(fname) img=PhotoImage(pilImage,master=image_zone) self.photofile=fname break except : self.photofile=None if self.photofile : w, h = img.width(), img.height() print('wh',w,h) if h>400 : print("reduction") img=PhotoImage(pilImage.resize((w//2,h//2), Image.ANTIALIAS),master=image_zone) image_zone=Button(self.card_win,image=img, command=self.choosePhoto) image_zone.image=img #image_zone.configure(image=image_zone.image,width=50,height=50,compound=RIGHT) #image_zone.pack() #print "IMAGE CHANGED" else : from os import path fname=self.name.replace(" ","_") if path.isfile("Cards/"+fname+".png") : image_zone.config(text='image can be taken from\n'+"Cards/"+fname+".png",background='white',anchor=CENTER) else : image_zone.config(text='clic to choose image',background='white',anchor=CENTER) #image_zone.pack() # POWER ZONE power_zone=PanedWindow(self.card_win, orient=VERTICAL) #fenetre=self.card_win.master def removePowerCreator(px) : def removePower(*args) : #print 'avant',list_pow self.bonus.remove(px) #print 'apres',list_pow #self.card_win.pack_forget() self.refreshWidget() return removePower for p in self.bonus : powline = PanedWindow(self.card_win, orient=HORIZONTAL) pow_wid=p.initWidget(powline) powline.add(pow_wid) removepow=Button(powline, text="X", command=removePowerCreator(p), anchor=E) removepow.pack() powline.add(removepow) power_zone.add(powline) def addPower(*args) : if addBonus.get()!= "add bonus": name=addBonus.get() else: name=add_cost_alteration.get() print ("added :",name) import CardPowers self.bonus+=[eval('CardPowers.'+name+'()')] self.bonus[-1].parent=self.bonus self.bonus[-1].card=self #self.card_win.pack_forget() self.refreshWidget() #Add bonus Option menu addBonus = StringVar(power_zone) addBonus.set("add bonus") # default value if not self.pv: addBonus_wid = Spell.getSpellMenu(power_zone, addBonus) else: addBonus_wid = getBonusMenu(power_zone, addBonus) addBonus.trace('w', addPower) if self.pv>0 or len(self.bonus)==0 or all([b.is_cost_alterator for b in self.bonus]): addBonus_wid.pack() #Add this to power zone power_zone.add(addBonus_wid) #Create save zone save_zone = PanedWindow(self.card_win, orient=HORIZONTAL) if self.monster_type != "all" and not(self.name in Card.blocked_creature) : save_wid = Button(save_zone, text="Save", command=self.postAndSave) elif self.monster_type != "all" : save_wid = Button(save_zone, text="creature in campaign", command=None) else: save_wid = Button(save_zone, text="nead type", command=None) save_wid.pack() #Create the open button save_zone.pack() if Card.monster_list.keys(): self.opening = StringVar(save_zone) self.opening.set("Open") choice = [na for na in Card.monster_list.keys() if na not in Card.blocked_creature] choice.sort() #print all_monsters.keys() open_wid = OptionMenu(save_zone, self.opening,*choice) self.opening.trace('w', self.Open) open_wid.pack() save_zone.add(open_wid) if Card.monster_list.keys(): self.delete = StringVar(save_zone) self.delete.set("Delete") choice = [na for na in Card.monster_list.keys() if na not in Card.blocked_creature] choice.sort() delete_wid = OptionMenu(save_zone, self.delete,*choice) self.delete.trace('w', self.clicDelete) delete_wid.pack() save_zone.add(delete_wid) #Create the type button self.category = StringVar(save_zone) self.category.set(self.monster_type) choice = [file2name(t,"_monsters.sav") for t in glob.glob("CardFiles/*_monsters.sav")] if "recup" in choice: choice.remove("recup") #print all_monsters.keys() category_wid = OptionMenu(save_zone, self.category,*choice) self.category.trace('w', self.setFile) category_wid.pack() #Add it to save zone save_zone.add(save_wid) save_zone.add(category_wid) #Create a new Strength zone for att and pv strength_zone=PanedWindow(self.card_win, orient=HORIZONTAL) att=StringVar() att.set(str(self.att)) pv=StringVar() ; pv.set(str(self.pv)) def modifiedAttPv(*args) : print ("modifiedAttPv") self.pv=int(pv.get()) if self.pv<1 and self.is_spell==False : if len(self.bonus)==0 : self.is_spell=True self.refreshWidget() else : self.pv=1 self.refreshWidget() if self.pv>0 and self.is_spell==True : if len(self.bonus)==0 : self.is_spell=False self.refreshWidget() else : self.pv=0 self.refreshWidget() self.att=int(att.get()) self.getCost() att_wid = Spinbox(strength_zone, from_=0, to=1000,textvariable=att,command=modifiedAttPv) att_wid.pack() strength_zone.add(att_wid) strength_zone.add(Label(strength_zone, text=' ', background='white', anchor=CENTER)) pv_wid = Spinbox(strength_zone, from_=0, to=1000,textvariable=pv,command=modifiedAttPv) pv_wid.pack() strength_zone.add(pv_wid) #Put it all in window self.card_win.add(name_zone) self.card_win.add(image_zone) self.card_win.add(power_zone) self.card_win.add(strength_zone) self.card_win.add(save_zone) self.card_win.pack()
gifdir = "D:/Projects/python/Gifs/" from sys import argv from tkinter import * from PIL.ImageTk import PhotoImage filename = argv[1] if len( argv) > 1 else '1.gif' # имя файла в командной строке? win = Tk() img = PhotoImage(file=gifdir + filename) can = Canvas(win) can.pack(fill=BOTH) can.config(width=img.width(), height=img.height()) # размер соответственно can.create_image(2, 2, image=img, anchor=NW) # картинке win.mainloop()
""" show one image with PIL photo replacement object handles many more image types; install PIL first: placed in Lib\site-packages """ import os, sys from tkinter import * from PIL.ImageTk import PhotoImage # <== use PIL replacement class # rest of code unchanged imgdir = 'images' imgfile = 'florida-2009-1.jpg' # does gif, jpg, png, tiff, etc. if len(sys.argv) > 1: imgfile = sys.argv[1] imgpath = os.path.join(imgdir, imgfile) win = Tk() win.title(imgfile) imgobj = PhotoImage(file=imgpath) # now JPEGs work! Label(win, image=imgobj).pack() win.mainloop() print(imgobj.width(), imgobj.height()) # show size in pixels on exit
#!/usr/local/bin/python #coding: utf-8 ''' Created on 2016年3月6日 @author: Calvin Wang ''' from learning.GUI.chapter2.imageButton import jpgdir from sys import argv from tkinter import * from PIL.ImageTk import PhotoImage filename = argv[1] if len(argv) > 1 else jpgdir # filename on cmdline? win = Tk() img = PhotoImage(file=filename) can = Canvas(win) can.pack(fill=BOTH) can.config(width=img.width(),height=img.height()) # set size to img's size can.create_image(2,2,image=img,anchor=NW) win.mainloop()
from PIL import Image from Script.Core import main_frame, game_type, cache_control textbox = main_frame.textbox image_data = {} image_text_data = {} image_lock = 0 cache: game_type.Cache = cache_control.cache """ 游戏缓存数据 """ image_dir_path = os.path.join("image") for image_file_path_id in os.listdir(image_dir_path): image_file_path = os.path.join(image_dir_path, image_file_path_id) image_file_name = image_file_path_id.rstrip(".png") old_image = PhotoImage(file=image_file_path) old_height = old_image.height() old_weight = old_image.width() font_scaling = main_frame.normal_font.measure("A") / 11 now_height = int(old_height * font_scaling) now_weight = int(old_weight * font_scaling) new_image = Image.open(image_file_path).resize((now_weight, now_height)) image_data[image_file_name] = PhotoImage(new_image) def print_image(image_name: str): """ 绘制图片的内部实现,按图片id将图片加入绘制队列 Keyword arguments: image_name -- 图片名字 image_path -- 图片路径 (default '') """ textbox.image_create(END, image=image_data[image_name])
""" отображает изображение с помощью стандартного объекта PhotoImage из библиотеки tkinter; данная реализация может работать с GIF-файлами, но не может обрабатывать изображения в формате JPEG; использует файл с изображением, имя которого указано в командной строке, или файл по умолчанию; используйте Canvas вместо Label, чтобы обеспечить возможность прокрутки, и т.д. """ import os, sys from tkinter import * from PIL.ImageTk import PhotoImage # импорт из PIL, хотя устанавливался Pillow - обертка для PIL !!! PIL устарел imgdir = 'images' imgfile = 'carmel.JPG' if len(sys.argv) > 1: # аргумент командной строки задан? imgfile = sys.argv[1] imgpath = os.path.join(imgdir, imgfile) win = Tk() win.title(imgfile) imgobj = PhotoImage(file=imgpath) Label(win, image=imgobj).pack() # прикрепить к метке Label print(imgobj.width(), imgobj.height()) # вывести размеры в пикселях, win.mainloop() # пока объект не уничтожен