class PrintText(): def __init__(self,canvas=canvas,x=x,y=y,text='',font="Arial 10",outline=bg,fill='yellow'): self.x=x self.y=y self.canvas=canvas self.text=text self.font=font canvas.delete('all') canvas.create_text(x,y,text=text,anchor='nw',fill=fill) y1=font.split(' ') y1=int(y1[1])+(int(y1[1])/2)+y x1=width-(x*2) canvas.create_rectangle(x,y,x1,y1,outline=outline) outline1=outline global x1,y1,outline1 def activateOutLine(event): xCoord=canvas.canvasx(event.x) yCoord=canvas.canvasx(event.y) outline=outline1 if x < xCoord < x1 and y < yCoord < y1: outline=activeOutLine canvas.create_rectangle(x,y,x1,y1,outline=outline) text='some text' PrintText(text=text) bodyOne.bind('<Motion>', PrintText.activateOutLine)
global x1,y1,outline1 нужны в функции событии activateOutLine
x1,y1 - будут меняться в процессе…
Вообщем делал я то что ниже, но сам уже начал запутываться в том что делаю и решил в классы… в которых до сих пор туплю.
import call import configurations from tkinter import * root = Tk() width=1024 height=768 x=root.winfo_screenwidth()/2-(width/2) y=root.winfo_screenheight()/2-(height/2) root.wm_geometry("+%d+%d" % (x, y)) root.geometry("1024x768") root.title('Стальной канат') colorBg='red' colorText='#07485b' colorActiveText='#0d6986' colorActiveOutLine='#0d6986' x=10 y=10 widthMenu=int(width*0.20) # ширина Главного Меню (слева) widthMenuBorder=widthMenu-(x*2) widthDb=int(width*0.35) widthDbSelect=int(width*0.44) print(widthDb) heightCanvass=height-100-6 bodyTop = Canvas(root, width=1020, height=98,bg=colorBg, cursor="hand2") bodyMenu = Canvas(root, width=widthMenu, height=heightCanvass,bg=colorBg, cursor="hand2") bodyDb = Canvas(root, width=widthDb, height=heightCanvass,bg=colorBg, cursor="hand2") bodyDbSelect = Canvas(root, width=widthDbSelect, height=heightCanvass,bg=colorBg, cursor="hand2") img = PhotoImage(file="img/logo.gif") bodyTop.create_image(8,10, image=img, anchor='nw') # координаты x, y coordsDb=[] coordsMenu=[] fontMenu=configurations.fontMenu fontSubMenu=configurations.fontSubMenu fontDb=configurations.fontDb fileMenu=call.callMenu() fileDb=call.callDb() fileArhive=call.callArhive def coordsForCanvss(xx=0,yy=0,body=bodyDb,fileName=0,coords=FALSE,font='Arial '+str(10), setCoords=FALSE,active=FALSE,fill=colorBg,activeBorder=colorBg): body.delete('all') # очистка холста nextY=font.split(' ') # берем из font цифровое значение 'Arial N' nextY=int(nextY[1])*2 # для "резинового" просчета следующей строки fileName=fileName.readlines() # содержимое файла заданного в fileName print('RRRRRRRR ',fileName) for i in fileName: if setCoords != False: # если перепечатывать строки то не создавать новые координаты a=[xx,yy] coords.append(a) # создаем новые координаты в список xRazbor=0 # параметр прибавления к Х one=i.split('*') if body == bodyMenu: # если печатаем меню, то только первое слово (второе идет на имя файла) one=one[:1] # вытаскиваем первое слово for getRazbor in one: # печатаем содержимое ONE от одног до нескольких слов if active==[xx,yy]: # цвета текста при фокусе мышью fill=colorActiveText if activeBorder==1: # цвет бордюра при фокусе мышью. НОЛЬ = цвет фона холста # 1 = colorActiveOutLine activeBorder=colorActiveOutLine bodyMenu.create_rectangle(xx,yy,xx+widthMenuBorder,yy+nextY, fill=colorBg,outline=activeBorder) else: fill=colorText body.create_text(xx+xRazbor+x+(x/2),yy,text=getRazbor,font=font,anchor='nw', fill=fill) xRazbor+=60 # + N пикселей к следующему слову yy+=nextY # + Y для следующей строки coordsForCanvss(xx=x,yy=y,body=bodyMenu,fileName=fileMenu,coords=coordsMenu,font='Arial '+str(fontMenu),setCoords=True) coordsForCanvss(xx=x,yy=y,body=bodyDb,fileName=fileDb,coords=coordsDb,setCoords=True) print(coordsMenu) def menuSelect(event): import call def menuPressed(event): getNewFile=enterMenu.split('*') getNewFile=str(getNewFile[1]) getNewFile=getNewFile.split('\n') fileName=getNewFile[0] fileName=open(fileName,'r') print(fileName) if enterMenu == True: coordsForCanvss(xx=x,yy=y,body=bodyDb,fileName=fileName,coords=coordsDb, font='Arial '+str(fontDb)) bodyMenu.delete('all') xCoord=bodyDb.canvasx(event.x) yCoord=bodyDb.canvasx(event.y) getFile=call.callMenu() enterMenu='' coordsForCanvss(xx=x,yy=y,body=bodyMenu,fileName=call.callMenu(),coords=coordsMenu, font='Arial '+str(fontMenu),fill=colorText) for i in coordsMenu: printString=getFile.readline() if i[0] < xCoord < i[0]+widthDb and i[1] < yCoord < i[1]+fontMenu+8: enterMenu=printString print('sdfsdfsd',enterMenu) coordsForCanvss(xx=x,yy=y,body=bodyMenu,fileName=call.callMenu(),coords=coordsMenu, font='Arial '+str(fontMenu),active=i,fill=colorText,activeBorder=1) bodyMenu.bind('<Button-1>', menuPressed) bodyMenu.bind('<Motion>',menuSelect) bodyTop.grid(row=0,column=0,columnspan=3,sticky='nw') bodyMenu.grid(row=1,column=0,sticky='nw') bodyDb.grid(row=1,column=1,sticky='nw') bodyDbSelect.grid(row=1,column=2,sticky='nw') mainloop()
Я уже подумываю заплатить кому нибудь, что бы разжевали мне КЛАССЫ по скайпу, нормальным языком…
Глянул тут, оказывается self делает переменную глобальную по всему классу, которую можно использовать в любой функции класса, когда читал Лутца до меня это не дошло.
Но я не могу сделать так в событии
def activateOutLine(self,event=NONE): self.event=event xCoord=canvas.canvasx(event.x) yCoord=canvas.canvasx(event.y) outline=self.outline if x < self.xCoord < self.x1 and y < self.yCoord < self.y1: outline=activeOutLine canvas.create_rectangle(x,y,self.x1,self.y1,outline=outline)
В event очень много информации. Посмотрите в документации.