当前位置: 首页>>代码示例>>Python>>正文


Python Canvas.create_image方法代码示例

本文整理汇总了Python中tkinter.Canvas.create_image方法的典型用法代码示例。如果您正苦于以下问题:Python Canvas.create_image方法的具体用法?Python Canvas.create_image怎么用?Python Canvas.create_image使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在tkinter.Canvas的用法示例。


在下文中一共展示了Canvas.create_image方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: CameraView

# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import create_image [as 别名]
class CameraView(View):
    def __init__(self, params):
        super(CameraView, self).__init__(params)

        self._multiplier = int(params["multiplier"]) if "multiplier" in params else 1
        self._multiplier = max(self._multiplier, 1)

        self._tk = Tk()
        self._canvas = Canvas(self._tk, width=80 * self._multiplier, height=60 * self._multiplier)

        self._tk.title("Camera view")
        self._tk.resizable(width=False, height=False)
        self._canvas.pack(side=tkinter.LEFT, fill=tkinter.BOTH, expand=True)

        self._tk.protocol("WM_DELETE_WINDOW", self.on_press_close)

        self._base_dir = "camera_" + str(int(time.time() * 1000))
        os.makedirs(self._base_dir)

    def run(self):
        super(CameraView, self).run()
        self._tk.mainloop()

    def on_new_input(self):
        try:
            hex_str = self.get_input()
            img = self._get_image(hex_str)
        except Exception as e:
            logging.debug(str(e))
            return
        if img is None:
            return

        bmp = ImageTk.BitmapImage(image=img, foreground="white", background="black")
        self._canvas.create_image(0, 0, image=bmp, anchor=tkinter.NW)
        self._tk_image = bmp

        img.save(self._base_dir + "/" + str(int(time.time() * 1000)) + ".png")

    def on_dismiss(self):
        self._tk.after_idle(self.on_press_close)

    def on_press_close(self):
        self._tk.destroy()
        self.join_io_thread()

    def _get_image(self, hex_str) -> Image:
        try:
            hex_data = binascii.unhexlify(hex_str)
            # Invert data from MCU
            hex_data = bytes([~h & 0xFF for h in hex_data])
        except TypeError as e:
            logging.debug(str(e))
            return

        img = Image.frombytes(mode="1", size=(80, 60), data=hex_data)
        img = img.resize((80 * self._multiplier, 60 * self._multiplier))
        return img
开发者ID:hkust-smartcar,项目名称:sc-studio,代码行数:60,代码来源:camera_view.py

示例2: loo_lumi

# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import create_image [as 别名]
def loo_lumi(aken, lume_pilt, kingi_pilt):
    """Create new snow, gifts and make both move with another function."""
    lumi = Canvas(aken, bg="Blue", highlightthickness=0, width=20, height=20)
    pilt = [lume_pilt, kingi_pilt]
    pilt = random.choice(pilt)
    positsioon_x = random.randint(0, 780)
    lumi.create_image(9, 9, image=pilt)
    lumi.pack()
    lumi.after(500, loo_lumi, aken, lume_pilt, kingi_pilt)
    lumesadu(aken, lumi, positsioon_x, 120)
开发者ID:rener2,项目名称:python-course,代码行数:12,代码来源:NeljasIseseisevYlesanne.py

示例3: demo1

# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import create_image [as 别名]
def demo1():
    try:
        
        if sys.version_info[0] == 3:
            from tkinter import Tk, Canvas, PhotoImage, NW, SW
        else:
            from Tkinter import Tk, Canvas, PhotoImage, NW, SW
    except ImportError:
        Tk = Canvas = None      

    if Tk: 
        from pykbool import connect
        
        contour = [(491.1025968497233, 19.886736214605065), (491.1025968497233, 5.524093392945851), (455.34269902086, 5.524093392945851), (455.34269902086, 19.886736214605065), (353.68241805023416, 17.677098857426728), (353.68241805023416, 8.838549428713364), (323.20136228182207, 8.838549428713364), (323.20136228182207, 17.677098857426728), (210.81311196253725, 14.362642821659207), (210.81311196253725, 3.3144560357675132), (175.05321413367392, 3.3144560357675132), (175.05321413367392, 14.362642821659207), (73.22264793529162, 14.362642821659207), (73.22264793529162, 10.0), (34.05704555129843, 10.0), (32.18390804597701, 110.48186785891704), (10.0, 110.48186785891704), (10.0, 162.40834575260803), (48.36100468284376, 156.88425235966218), (75.09578544061303, 156.88425235966218), (128.56534695615156, 162.40834575260803), (178.62920391656024, 176.77098857426725), (226.81992337164752, 196.65772478887232), (249.9787143465304, 211.02036761053148), (291.18773946360153, 246.374565325385), (328.65048957002983, 283.9384003974168), (337.5053214133674, 298.30104321907595), (337.5053214133674, 341.3889716840536), (448.1907194550873, 350.22752111276696), (448.1907194550873, 333.6552409339294), (685.7386121753938, 350.22752111276696), (683.8654746700724, 356.856433184302), (771.3920817369094, 364.5901639344262), (774.9680715197957, 318.18777943368104), (767.816091954023, 318.18777943368104), (789.272030651341, 60.765027322404364), (796.4240102171137, 60.765027322404364), (800.0, 8.838549428713364), (757.088122605364, 8.838549428713364), (757.088122605364, 23.20119225037257), (644.6998722860792, 19.886736214605065), (644.6998722860792, 8.838549428713364), (610.8131119625373, 5.524093392945851), (608.9399744572158, 19.886736214605065)]
        holea = [(162.62239250744997, 127.0541480377546), (189.35717326521925, 135.89269746646795), (239.42103022562793, 159.09388971684052), (287.6117496807152, 187.81917536015894), (308.8974031502767, 205.49627421758566), (348.2332907620264, 246.374565325385), (366.1132396764581, 266.26130153999003), (389.272030651341, 301.6154992548435), (450.0638569604087, 307.13959264778936), (451.7667092379736, 57.45057128663686), (355.38527032779905, 55.24093392945852), (355.38527032779905, 66.28912071535022), (323.20136228182207, 66.28912071535022), (323.20136228182207, 55.24093392945852), (210.81311196253725, 55.24093392945852), (210.81311196253725, 60.765027322404364), (173.35036185610898, 60.765027322404364), (173.35036185610898, 55.24093392945852), (73.22264793529162, 51.926477893691), (71.51979565772669, 116.00596125186286), (107.27969348659005, 119.32041728763039)]
        holeb = [(749.9361430395913, 60.765027322404364), (498.254576415496, 57.45057128663686), (494.67858663260967, 294.9865871833085), (566.0280970625798, 301.6154992548435), (566.0280970625798, 292.77694982613014), (591.0600255427842, 292.77694982613014), (589.3571732652192, 303.8251366120218), (730.3533418475947, 315.9781420765027)]
          
        connected_polygon = connect([contour, holea, holeb])

        root = Tk()
        root.title(string='connect holes to contour / fill resulting polygon')
        canvas1 = Canvas(root, width=900, height=415, background='white')
        canvas1.pack()

        canvas1.create_polygon(contour, outline='blue', fill='')
        canvas1.create_text(contour[0], text='C(1)')
        canvas1.create_text(contour[20], text='C(i)')
        canvas1.create_text(contour[-1], text='C(n)')

        canvas1.create_polygon(holea, outline='red', fill='')
        canvas1.create_text(holea[0], text='H1(1)')
        canvas1.create_text(holea[9], text='H1(i)')
        canvas1.create_text(holea[-1], text='H1(n)')

        canvas1.create_polygon(holeb, outline='green', fill='')
        canvas1.create_text(holeb[0], text='H2(1)')
        canvas1.create_text(holeb[2], text='H2(i)')
        canvas1.create_text(holeb[-1], text='H2(n)')
        
        canvas1.create_text((10, 350), text='# More info in setup.py\n'
            'from pykbool import connect\n'
            'contour=[(... , ...) ... ]; hole1=[(... , ...) ... ]; hole2=...\n'
            'polygon=connect([contour, hole1, hole2, ...])', anchor=SW)
        
        canvas2 = Canvas(root, width=900, height=415, background='white')
        canvas2.pack()
        image=PhotoImage(file=os.path.join('data','demo.gif'))
        canvas2.create_image((0,0), image=image, anchor=NW)
        canvas2.image=image
        canvas2.create_polygon(connected_polygon, outline='black', fill='grey')
        canvas2.create_text(connected_polygon[0], text='P1')
        canvas2.create_text(connected_polygon[62], text='Pi')
        canvas2.create_text(connected_polygon[-1], text='Pn')

        root.mainloop()
开发者ID:decitre,项目名称:pykbool,代码行数:57,代码来源:setup.py

示例4: TkWindow

# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import create_image [as 别名]
class TkWindow(tkinter.Tk):
    def __init__(self,parent):
        tkinter.Tk.__init__(self,parent)
        self.parent = parent
        self.initialize()

    def initialize(self):
        self.grid()

        buttonFile = tkinter.Button(self,text=u"Get file",command=self.getFile)
        buttonFile.grid(column=0,row=1,sticky='EW',padx=10,pady=10)

        buttonCrypto = tkinter.Button(self,text=u"Crypto",command=self.crypto)
        buttonCrypto.grid(column=0,row=3,sticky='EW',padx=10,pady=10)

        #labelHeader = Tkinter.Label(self,text=u"Database file:",anchor="w")
        #labelHeader.grid(column=0,row=0,columnspan=3,padx=10,pady=10,sticky='EW')
        self.labelVariable = tkinter.StringVar()
        labelFileName = tkinter.Label(self,textvariable=self.labelVariable,anchor="w",fg="black",bg="white")
        labelFileName.grid(column=1,row=1,columnspan=2,sticky='EW',padx=10,pady=10)

        self.canvas = Canvas(self,width=400, height=400,bd=0,bg="blue")
        self.canvas.grid(row = 2,column = 0,columnspan=2,sticky='EW',padx=10,pady=10)
        #self.photo = ImageTk.PhotoImage(file = "/home/paulina/obrazki/obrazek.jpg")
        #self.canvas.create_image(0,0, image = self.photo)


    def getFile(self):
        self.fileName = filedialog.askopenfilename(initialdir = "/home/paulina/obrazki",title = "choose your file",filetypes = (("jpeg files","*.jpg"),("all files","*.*")))
        self.labelVariable.set(self.fileName)

        self.photo = Image.open(self.fileName)
        (imageSizeWidth, imageSizeHeight) = self.photo.size
        print(imageSizeWidth, imageSizeHeight)

        newImageSizeHeight = 400
        n = imageSizeHeight/newImageSizeHeight
        print(n)
        newImageSizeWidth = int(imageSizeWidth/n)
        print(newImageSizeWidth, newImageSizeHeight)

        self.canvas.config(width=newImageSizeWidth,height=newImageSizeHeight)
        self.photo = self.photo.resize((newImageSizeWidth, newImageSizeHeight), Image.ANTIALIAS)
        self.photo = ImageTk.PhotoImage(self.photo)
        self.canvas.create_image(int(newImageSizeWidth/2), int(newImageSizeHeight/2), image = self.photo)

    def crypto(self):
        obj = AES.new('This is a key123', AES.MODE_CBC, 'This is an IV456')
        message = "The answer is no"
        ciphertext = obj.encrypt(message)
        print(ciphertext)
        obj2 = AES.new('This is a key123', AES.MODE_CBC, 'This is an IV456')
        messagedec = obj2.decrypt(ciphertext)
        print(messagedec)
开发者ID:PaulinaWrobel,项目名称:CryptographicEmbeddedSystem,代码行数:56,代码来源:ClassCES_p.py

示例5: progress

# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import create_image [as 别名]
 def progress( self ):
     o=os.popen("cd {0} && snakemake --dryrun --rerun-incomplete > {0}/Reports/checkpoint".format(self.workpath.get()))
     o.close()
     F=open("{0}/Reports/checkpoint".format(self.workpath.get()),"r").read()
     rules2={}
     rules=re.findall(r'rule .+:',F)
     for i in rules:
         i=re.sub("rule ","",i)
         i=re.sub(":","",i)
         rules2[i]=0
 
 
     F=open("{0}/Reports/{1}.dot".format(self.workpath.get(), self.Pipeline.get() ),"r").read()
     for i in rules2.keys():
         F=re.sub(r'('+i+')(\".+?)\".+?\"',r'\1_pending\2"0.0 0.0 0.0"',F)
 #        F=re.sub(i,"",F)
 
 
     G=open("{0}/Reports/{1}-{2}.dot".format(self.workpath.get(),self.Pipeline.get(),"progress"),"w")
     G.write(F)
     G.close()
 
     o=os.popen("cd {0}/Reports && dot -Tpng -o {0}/Reports/{1}-progress.png {0}/Reports/{1}-progress.dot;convert {0}/Reports/{1}-progress.png {0}/Reports/{1}-progress.gif".format(self.workpath.get(),self.Pipeline.get()))
 
 #    tkinter.messagebox.showerror("o",o)
 
     PL=self.Pipeline.get() #pipelineget()
     gf=Toplevel()
 
     gf.title("CCBR Pipeliner: {0} Progress Graph".format(PL))
     cgf = Canvas(gf,bg="white")
 #    gff=Frame(cgf,width=300,height=300)
     xscrollbar = Scrollbar(gf, orient=HORIZONTAL)
     xscrollbar.pack(side = BOTTOM, fill=X )
     xscrollbar.config(command=cgf.xview)
 
     yscrollbar = Scrollbar(gf,orient=VERTICAL)
     yscrollbar.pack(side = RIGHT, fill=Y )
     yscrollbar.config(command=cgf.yview)
 
     cgf.config(xscrollcommand=xscrollbar.set, yscrollcommand=yscrollbar.set)
     cgf.config(width=600,height=600)
     cgf.pack(expand=1,fill=BOTH,side=RIGHT)
     cgf.config(scrollregion=(0,0,1000,5000))
     try:
         time.sleep(5)
         img = PhotoImage(file="{0}/Reports/{1}-progress.gif".format(self.workpath.get(),PL))
     except:
         time.sleep(5)
         img = PhotoImage(file="{0}/Reports/{1}-progress.gif".format(self.workpath.get(),PL))
     cgf.create_image(0,0,image=img, anchor="nw")
     cgf.image=img
开发者ID:felloumi,项目名称:Pipeliner,代码行数:54,代码来源:frame.py

示例6: __init__

# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import create_image [as 别名]
	def __init__(self, image, COLORFLAG = False):
		self.img = PhotoImage(width = WIDTH, height = HEIGHT)
		for row in range(HEIGHT): 
			for col in range(WIDTH):
				num = image[row*WIDTH + col]
				if COLORFLAG == True:
					kolor = '#%02x%02x%02x' % (num[0], num[1], num[2])
				else:
					kolor = '#%02x%02x%02x' % (num, num, num)
				self.img.put(kolor, (col, row))
		c = Canvas(root, width = WIDTH, height = HEIGHT); c.pack()
		c.create_image(0, 0, image = self.img, anchor = NW)
		printElapsedTime('displayed image')
开发者ID:swkarlekar,项目名称:STIDER_work,代码行数:15,代码来源:machineVision.py

示例7: loo_pilv

# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import create_image [as 别名]
def loo_pilv(aken, pildi_list, mitu_pilve):
    """Create desired amount of clouds and call out a function to make them move."""
    arv = 0
    pilve_koht_x = 0
    while mitu_pilve != arv:
        kiirus = 30
        pilt = random.choice(pildi_list)
        pilv = Canvas(aken, width=100, height=55, bg="blue", highlightthickness=0)
        pilv.create_image(50, 30, image=pilt)
        pilv.place(x=pilve_koht_x, y=0)
        pilv.pack()
        pilve_koht_y = random.randint(0, 85)
        liiguta_pilve(pilv, pilve_koht_x, pilve_koht_y, kiirus, aken, pildi_list)
        pilve_koht_x += 100
        arv += 1
开发者ID:rener2,项目名称:python-course,代码行数:17,代码来源:NeljasIseseisevYlesanne.py

示例8: __init__

# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import create_image [as 别名]
	def __init__(self, root, x1, y1, x2, y2):

		t = time.time()
		self.img = PhotoImage(width=wid, height=hei)

		canv = Canvas(root, width = wid, height = hei)
		canv.pack()
		canv.create_image(0, 0, image = self.img, anchor=NW)

		dx = abs(x2-x1)/wid
		dy = abs(y2-y1)/hei

		#c = complex(-0.8, 0.156)
		#c = complex(-0.74543,+0.11301)
		#c = complex(-0.1,0.651)
		#c = complex(-0.70176,-0.3842)
		c = complex(-0.835,-0.2321)
		#c = complex(-0.74434, -0.10772)
		#c = complex(-0.62772, 0.42193)

		y = y1
		for j in range(hei):
			line = '{'
			x = x1
			
			for i in range(wid):

				x = x + dx
				a = complex(x, y)

				for k in range(maxiter):
					a = a*a + c
					if(abs(a) > blowup):
						break
				if(k == maxiter-1):
					#line += '#%02x%02x%02x ' % (255,255,255)
					line += '#%02x%02x%02x ' % (0,0,0)
				else:
					
					line += '#%02x%02x%02x ' % color(k)

			line += '}'
			self.img.put(line, (0, j))
			canv.update()
			y = y - dy
			
		print(time.time() - t)
开发者ID:nightmarebadger,项目名称:Julia-sets,代码行数:49,代码来源:mandelbrot.py

示例9: __init__

# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import create_image [as 别名]
    def __init__(self, region_list=None, player_list=None, canvas:tk.Canvas=None):
        if player_list is None:
            # player_list 가 없는 경우에는 자동으로 constant.PLAYER_NO 에 해당하는 만큼 player 를 생성해서 넣는다.
            self.__player_list = []
            for i in range(constant.PLAYER_NO):
                self.__player_list.append(player.Player())
        else:
            # player_list 가 있는 경우에는 이것을 사용하고 알맞은 플레이어 수로 업데이트한다.
            self.__player_list = player_list
            constant.PLAYER_NO = len(player_list)

        self.__region_list = region_list  # 맵에 있는 모든 땅의 정보를 의미한다.
        assert len(region_list) == constant.TOTAL_REGIONS
        self.__current_turn = 0  # 현재 턴 수
        self.__canvas = canvas
        self.__dices_list = [dice.Dice(), dice.Dice()]
        canvas.create_image(275, 350, anchor=tk.NW, image=self.__dices_list[0])
        canvas.create_image(375, 350, anchor=tk.NW, image=self.__dices_list[1])
开发者ID:humit0,项目名称:Final_Project,代码行数:20,代码来源:game.py

示例10: workflow

# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import create_image [as 别名]
    def workflow(self):
        PL=self.Pipeline.get() #pipelineget()
        gf=Toplevel()
        #MkaS=os.popen("./makeasnake.py 2>&1 | tee -a "+workpath.get()+"/Reports/makeasnake.log").read()
    
        gf.title("CCBR Pipeliner: "+ PL + " Workflow Graph")
        cgf = Canvas(gf,bg="white")
        #gff=Frame(cgf,width=300,height=300)
        xscrollbar = Scrollbar(gf, orient=HORIZONTAL)
        xscrollbar.pack(side = BOTTOM, fill=X )
        xscrollbar.config(command=cgf.xview)

        yscrollbar = Scrollbar(gf,orient=VERTICAL)
        yscrollbar.pack(side = RIGHT, fill=Y )
        yscrollbar.config(command=cgf.yview)

        cgf.config(xscrollcommand=xscrollbar.set, yscrollcommand=yscrollbar.set)
        cgf.config(width=600,height=600)
        cgf.pack(expand=1,fill=BOTH,side=RIGHT)
        cgf.config(scrollregion=(0,0,5000,20000))
        img = PhotoImage(file=self.workpath.get()+"/Reports/"+PL+".gif")
        cgf.create_image(0,0,image=img, anchor="nw")
        cgf.image=img
开发者ID:felloumi,项目名称:Pipeliner,代码行数:25,代码来源:frame.py

示例11: display_mandelbrot

# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import create_image [as 别名]
def display_mandelbrot():
    width = 700
    height = 700
    window = Tk()
    canvas = Canvas(window, width=width, height=height, bg="#ffffff")
    canvas.pack()
    img = PhotoImage(width=width, height=height)
    canvas.create_image((width//2, height//2), image=img, state="normal")

    real_range = (-2.25, .75)
    imag_range = (-1.5, 1.5)
    precision = 0.003
    max_iterations = 20

    real_to_x_mapper = make_linear_mapper(real_range, (0, width), int_out=True)
    imag_to_y_mapper = make_linear_mapper(imag_range, (0, height), int_out=True)

    color_mapper = make_color_mapper(max_iterations)

    m_set = calc_mandelbrot_for_range(real_range[0], real_range[1], imag_range[0],
                                      imag_range[1], precision, max_iterations)
    for item in m_set:
        point, result = item
        (x, y) = point
        x_pixel = real_to_x_mapper(x)
        y_pixel = imag_to_y_mapper(y)
        (in_mandelbrot_set, z_cur, steps_taken) = result

        color = "#000000"
        if not in_mandelbrot_set:
            color = color_mapper(steps_taken)
        
        print("plotting: {}, {} -> {}".format(x_pixel, y_pixel, color))
        img.put(color, (x_pixel, y_pixel))

    mainloop()
开发者ID:calebmadrigal,项目名称:mandelbrot-py,代码行数:38,代码来源:mandelbrot.py

示例12: ApplicationUI

# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import create_image [as 别名]
class ApplicationUI(tkinter.Frame):

	def __init__(self, master = None):
		master.minsize(width=550, height=450)
		master.maxsize(width=550, height=450)
		tkinter.Frame.__init__(self, master)
		self.grid()
		self.pack()
		self.createWidgets()
		

	def createWidgets(self):
		self.title = Label(self, text="Image!", font=("Helvetica", 16))
		self.title.grid(row=0, column=1, columnspan=2)

		self.open_file = Button(self)
		self.open_file['text'] = "OPEN"
		self.open_file["command"] = self.openfile
		self.open_file.grid(row=1, column=0)

		self.save_button = Button(self, text='SAVE',
									command=self.save_file)
		self.save_button.grid(row=1, column=1)

		self.canvas = Canvas(self, width=400, height=300)
		self.canvas.grid(row=2, column=0, rowspan=5, columnspan=4)

		self.convert_grayscale_button= Button(self)
		self.convert_grayscale_button['text'] = "Convert to\n grayscale"
		self.convert_grayscale_button["command"] = self.convert_grayscale
		self.convert_grayscale_button.grid(row=7, column=0)

		self.variable = StringVar(self)
		self.variable.set("gray") 
		self.choose_color_menu = OptionMenu(self, self.variable,"gray", "blue", "green", "red")
		self.choose_color_menu['text'] = "Choose Color"
		self.choose_color_menu.grid(row=7, column=1)
					
		self.color_button = Button(self, text="COLOR", command=self.color_image)
		self.color_button.grid(row=7, column=2)

		self.quit_button = Button(self, text="QUIT", command=self.quit)
		self.quit_button.grid(row=7, column=3)
	
	def openfile(self):
		self.filename = askopenfilename()
		self.pilImage = Image.open(self.filename)
		width, height = self.pilImage.size
		rate = 400/width
		new_width = 400
		new_height = int(height*rate)
		print (new_width, new_height)
		self.pilImage=self.pilImage.resize((new_width, new_height), Image.ANTIALIAS)
		self.image = ImageTk.PhotoImage(self.pilImage)
		self.canvas.create_image(250, 200, image=self.image, anchor='center')

	def save_file(self):
		self.filename=asksaveasfilename()
		with open(self.filename, 'wb') as f:
			self.backwards.export(f.name, format="png")

	def quit(self):
		if hasattr(self, 'player'):
			os.remove(TEMP_FILE)
		root.destroy()

	def choose_color(self):
		self.color = self.variable.get()


	def color_image(self):
		if hasattr(self, 'grayImage'):
			self.choose_color()
			if self.color == 'blue':
				color = '#0000FF'
			elif self.color == 'red':
				color = '#FF0000'
			elif self.color == 'green':
				color = '#00FF00'
			self.coloredImg = ImageOps.colorize(self.grayImage, (0,0,0,0), color)
			self.image = ImageTk.PhotoImage(self.coloredImg)
			self.canvas.create_image(250, 200, image=self.image, anchor='center')
		else:
			tkMessageBox.showinfo('Warning', "Convert the file to grayscale first")

	def convert_grayscale(self):
		self.grayImage = self.pilImage.convert('L')
		self.image = ImageTk.PhotoImage(self.grayImage)
		self.canvas.create_image(250, 200, image=self.image, anchor='center')
开发者ID:alexacristina,项目名称:ms_assignments,代码行数:91,代码来源:image_manipulation.py

示例13: range

# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import create_image [as 别名]
    #color string table in Photoimage format #RRGGBB 
    clr=[ ' #%02x%02x%02x' % (int(255*((i/255)**.25)),0,0) for i in range(256)]
    clr.append(' #000000')  #append the color of the centre as index 256
    #calculate mandelbrot x,y coordinates for each screen pixel
    xm=[xa + (xb - xa) * kx /x  for kx in range(x)]
    ym=[ya + (yb - ya) * ky /y  for ky in range(y)]
    #build the Photoimage string by calling mandel_pixel to index in the color table
    return" ".join((("{"+" ".join(clr[mandel_pixel(complex(i,j))] for i in xm))+"}" for j in ym))



#window size
x=640
y=480
#corners of  the mandelbrot plan to display  
xa = -2.0; xb = 1.0
ya = -1.27; yb = 1.27

#Tkinter window
window = Tk()
canvas = Canvas(window, width = x, height = y, bg = "#000000");canvas.pack()
img = PhotoImage(width = x, height = y)
canvas.create_image((0, 0), image = img, state = "normal", anchor = NW)

#do the mandelbrot 
t1=clock()
img.put(mandelbrot(xa,xb,ya,yb,x,y))
print(clock()-t1, ' seconds')

mainloop()
开发者ID:jacob-carrier,项目名称:code,代码行数:32,代码来源:recipe-579048.py

示例14: gui_view_tk

# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import create_image [as 别名]
class gui_view_tk(Tkinter.Tk):
    """
    Class to manage the display of a saved text based 
    grid map in a GUI - useful for large grids
    Grid text sample is below:
        ..#......2#XXXXX.............X.X......X.
        ..#......A#XXXX.............XX.......X..
        ..#.A0000A#XXXX...X.XX......XXT......XXX
        ......111A#XXXX....X..X...XXXXX........X
        .....A1...#X..X..XXXXXXX...X.XX........X
    """
    def __init__(self,parent):
        """
        initialise tkinter with default parameters
        """
        Tkinter.Tk.__init__(self,parent)
        self.parent = parent
        self.appWidth = 1900   # initial values
        self.appHeight = 1000
        self.cell_width = 4
        self.cell_height = 3
        self.fname = ''
        self.screenWidth = self.winfo_screenwidth()
        self.screenHeight = self.winfo_screenheight()
        self.configure(bg='black')
        self.geometry('%dx%d+%d+%d' % (self.appWidth, self.appHeight, self.screenWidth - self.appWidth - 0, self.screenHeight - self.appHeight - 0))

        WIDTH = self.appWidth
        HEIGHT = self.appHeight
        self.canvas = Canvas(self, width=WIDTH, height=HEIGHT, bg="#000000")
        self.canvas.pack()
        self.img = PhotoImage(width=WIDTH, height=HEIGHT)
        self.canvas.create_image(( WIDTH/2,  HEIGHT/2), image=self.img, state="normal")
        #self.TEST_sin()   # testing - draws a sin wave
        self.appWidth = 1900   # canvas.width
        self.appHeight = 1000
        self.canvas.pack()
        
    def TEST_sin(self):    
        for x in range(4 * self.appWidth):
            y = int(self.appHeight/2 + self.appHeight/4 * math.sin(x/80.0))
            self.img.put("#ffffff", (x//4,y))
        self.canvas.pack()
    
    def add_file(self, fname):
        self.fname = fname
    
    def show_grid_from_file(self, fname):
        """
        reads a saved grid file and paints it on the canvas
        """
        with open(fname, "r") as f:
            for y, row in enumerate(f):
                for x, val in enumerate(row):
                    self.draw_cell(y, x, val)


    def draw_cell(self, row, col, val):
        """
        draw a cell as position row, col containing val
        """
        if val == 'T':
            self.paint_target(row,col)
        elif val == '#':
            self.paint_block(row,col)
        elif val == 'X':
            self.paint_hill(row,col)
        elif val == '.':
            self.paint_land(row,col)
        elif val in ['A']:
            self.paint_agent_location(row,col)
        elif val in ['1','2','3','4','5','6','7','8','9']:
            self.paint_agent_trail(row,col, val)
    
    def put_standard_block(self, y, x, val):
        """
        prints a block, packing out around the y/x location
        with pixels up to cell width and cell height
        """
        for j in range(0,self.cell_height):
            for i in range(0,self.cell_width):
                self.img.put(val, (x*self.cell_width+i, y*self.cell_height+j))
    
    def paint_land(self, y, x):
        self.put_standard_block(y,x,'bisque')
        
    def paint_block(self, y, x):
        self.put_standard_block(y,x,'gray9')

    def paint_hill(self, y, x):
        self.put_standard_block(y,x,'green4')

    def paint_target(self, y, x):
        self.put_standard_block(y,x,'yellow')
        self.img.put('black', (x*self.cell_width+1, y*self.cell_height+1))
        self.img.put('black', (x*self.cell_width+0, y*self.cell_height+1))
        self.img.put('black', (x*self.cell_width+1, y*self.cell_height+0))
        self.img.put('black', (x*self.cell_width+0, y*self.cell_height+0))

    def paint_agent_trail(self, y, x, val):
#.........这里部分代码省略.........
开发者ID:gitter-badger,项目名称:AIKIF,代码行数:103,代码来源:gui_view_world.py

示例15: take_screenshot_crop

# 需要导入模块: from tkinter import Canvas [as 别名]
# 或者: from tkinter.Canvas import create_image [as 别名]
def take_screenshot_crop(path):
    pimage = _r.take_screenshot()

    _, _, width, height = pimage.getbbox()

    displays = _r.get_display_monitors()
    leftmost, topmost = 0, 0
    for d in displays:
        if d[0] < leftmost:
            leftmost = d[0]
        if d[1] < topmost:
            topmost = d[1]

    root = Tk()  # Creates a Tkinter window
    root.overrideredirect(True)  # Makes the window borderless
    root.geometry("{0}x{1}+{2}+{3}".format(width, height, leftmost, topmost))  # window size = screenshot size
    root.config(cursor="crosshair")  # Sets the cursor to a crosshair

    pimage_tk = ImageTk.PhotoImage(pimage)  # Converts the PIL.Image into a Tkinter compatible PhotoImage

    can = Canvas(root, width=width, height=height)  # Creates a canvas object on the window
    can.pack()
    can.create_image((0, 0), image=pimage_tk, anchor="nw")  # Draws the screenshot onto the canvas

    # This class holds some information about the drawn rectangle
    class CanInfo:
        rect = None
        startx, starty = 0, 0

    # Stores the starting position of the drawn rectangle in the CanInfo class
    def xy(event):
        CanInfo.startx, CanInfo.starty = event.x, event.y

    # Redraws the rectangle when the cursor has been moved
    def capture_motion(event):
        can.delete(CanInfo.rect)
        CanInfo.rect = can.create_rectangle(CanInfo.startx, CanInfo.starty, event.x, event.y)

    # Cancels screen capture
    def cancel(event):
        if event.keycode == 27:  # cancel when pressing ESC
            root.destroy()

    # Saves the image when the user releases the left mouse button
    def save_img(event):
        startx, starty = CanInfo.startx, CanInfo.starty
        endx, endy = event.x, event.y

        # Puts the starting point in the upper left and the ending point in the lower right corner of the rectangle
        if startx > endx:
            startx, endx = endx, startx
        if starty > endy:
            starty, endy = endy, starty

        crop_image = pimage.crop((startx, starty, endx, endy))
        crop_image.save(path, "PNG")
        root.destroy()  # Closes the Tkinter window

    # Binds mouse actions to the functions defined above
    can.bind("<KeyPress>", cancel)
    can.bind("<Button-1>", xy)
    can.bind("<B1-Motion>", capture_motion)
    can.bind("<ButtonRelease-1>", save_img)

    can.focus_force() # Force focus of capture screen
    root.mainloop()  # Shows the Tk window and loops until it is closed
开发者ID:instantshare,项目名称:instantshare,代码行数:68,代码来源:windows_tk.py


注:本文中的tkinter.Canvas.create_image方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。